问题描述
所以我一直在尝试使用 postgREST 从 postgres 数据库中获取一些值,将它们显示在带有 vuetify 的表中,并在每个值旁边都有复选框,以便用户可以从表中删除一行。
我的问题是我不知道如何从复选框中获取选定的值,或者更好的是只获取 ID 列并在我的脚本中使用它们。
我的 html:
<template>
<p v-if="state == 'error' " class="red">{{ error }}</p>
<div v-else-if="state == 'ready' ">
<div id="app">
<v-app id="inspire">
<button style="font-face: 'Comic Sans MS'; font-size: larger; color: white; background-color: #1e1e1e; " v-on:click="greet">Delete</button>
<h5 style="font-face: 'Comic Sans MS'; font-size: larger; color: white; background-color: #1e1e1e; " >Selected: {{ selected }}</h5>
<v-data-table dark
v-model="selected"
:headers="headers"
:items="exa_tb"
item-key="id"
select-all
show-select
:items-per-page="3"
class="elevation-1">
</v-data-table>
<button style="font-face: 'Comic Sans MS'; font-size: larger; color: white; background-color: #1e1e1e; " onClick="window.location.reload();">Refresh Page</button>
</v-app>
</div>
</div>
<p v-else-if="state == 'loading' "> Loading Messages...</p>
</template>
我的 javasript :
<script>
export default {
data () {
return {
singleSelect: false,selected: [],headers: [{
text: 'ID',align: 'start',sortable: false,value: 'id',},{ text: 'Message',value: 'msg' },{ text: 'Timestamp',value: 'timesmp' },],exa_tb: [],error: '',state: 'loading',}
},created(){
this.loadExa_tb();
},methods: {
greet: function () {
if(confirm('Are you sure you want to delete this item?')){
for(var i = 1; i <=this.selected.length; i++){
var delete_this = //with the value from the selected checkBox
fetch('http://localhost:3000/exa_tb?id=eq.' + delete_this,{
method: 'DELETE',})
.then(res => res.text())
.then(res => console.log(res))
}
}
},async loadExa_tb(){
try {
const exa_tb = await fetch('http://localhost:3000/exa_tb');
this.exa_tb = await exa_tb.json();
this.state = 'ready';
} catch(err) {
this.error = err;
this.state = 'error';
}
},}
};
</script>
解决方法
您只需从数组中获取值:
var delete_this = selected[i].id
还有数组索引从 0 开始,你的 for 循环从 1 开始。所以你也必须改变你的 for 循环
,如您所见,您的数据表模型已被“选中”。由于它是一个反应性属性,因此它始终会为每个选定的行存储一个数组,您可以在例如 greet 方法中使用它:
methods: {
greet: function () {
if(confirm('Are you sure you want to delete this item?')){
for(var i = 0; i <this.selected.length; i++){
console.log(this.selected[i].id) // Inspect ids of selected items
var delete_this = this.selected[i].id
fetch('http://localhost:3000/exa_tb?id=eq.' + delete_this,{
method: 'DELETE',})
.then(res => res.text())
.then(res => console.log(res))
}
}
},