vue+vuetify中實作表格的可編輯功能
- 最近在做vue的項目中遇到一個需要實作表格可編輯功能的需求,又因為項目選用的UI庫為vuetify,認真研究了vuetify官網,并沒有可編輯表格的說明。于是,自己查閱資料實作了這個需求。
<v-simple-table id="tab">
<template v-slot:default>
<thead>
<!-- 表頭 -->
<tr>
<th class="text-left pa-0">Type</th>
<th class="text-left pa-0">Sitelan IP</th>
<th class="text-left pa-0">console IP</th>
<th class="text-left pa-0">console Port</th>
<th class="text-left pa-0">SN</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
<tr v-for="item in desserts" :key="item.id">
<td>
<v-text-field
v-model="item.duType"
:readonly="item.readonly"
autofocus
></v-text-field>
</td>
<td>
<v-text-field
v-model="item.sitelanIp"
:readonly="item.readonly"
autofocus
></v-text-field>
</td>
<td>
<v-text-field
v-model="item.consoleIp"
:readonly="item.readonly"
autofocus
></v-text-field>
</td>
<td>
<v-text-field
v-model="item.consolePort"
:readonly="item.readonly"
autofocus
></v-text-field>
</td>
<!-- <td>
<v-text-field
v-model="item.protein"
:readonly="item.readonly"
autofocus
></v-text-field>
</td> -->
<td>
<v-text-field
v-model="item.sn"
:readonly="item.readonly"
autofocus
></v-text-field>
</td>
<template>
<!-- 按鈕區域 -->
<td>
<!-- 非修改界面顯示修改,修改界面顯示儲存 -->
<v-btn rounded color="primary" dark @click="editItem(item)" small >{{ item.readonly? "修改":"儲存" }}</v-btn>
<!-- 非修改界面顯示删除 -->
<v-btn rounded color="error" dark small v-if="item.readonly" @click="delItem(item)">删除</v-btn>
<!-- 修改界面顯示取消 -->
<v-btn rounded color="success" dark small v-if="!item.readonly" @click="cancelItem(item)">取消</v-btn>
</td>
</template>
</tr>
</tbody>
</template>
</v-simple-table>
<script>
export default {
data () {
return {
// 表格資料
desserts: [
],
editedItem: {
id: 0,
name: '',
calories: 0,
fat: 0,
carbs: 0,
protein: 0,
iron: '',
readonly: true
},
editedIndex: -1,
stpId:12131312,
}
},
created() {
this.fetchData(this.stpId);
},
methods: {
//請求背景傳回資料
fetchData(stpId) {
//自己的請求接口(就口的每一條資料得有一個‘readonly’的開關控制本條資料是否開啟編輯)
xxxxxxxxxxxxxx(stpId).then((res) => {
this.desserts = res.data;
});
},
// 修改資料(儲存資料)
editItem(item) {
this.editedIndex = this.desserts.indexOf(item);//先找到desserts數組裡面對應的索引,通俗點說就是确定修改哪一行資料
this.editedItem = Object.assign({}, item);//把未修改之前的值存到editedItem對象裡面,友善使用者取消修改
//以上兩行主要是為取消修改服務,要實作修改其實隻需下面一行就夠了,因為html中本身的标簽為<v-text-field>,也就是說隻需控制它的隻讀和非隻讀來回切換即可做到修改儲存
item.readonly = !item.readonly;
},
// 删除資料
delItem(item) {
const index = this.desserts.indexOf(item);//找到desserts數組裡面對應的索引,通俗點說就是确定删除哪一行資料
confirm('Are you sure you want to delete this item?') && this.desserts.splice(index, 1);//系統彈出确認框,點選确定就是删除這一行資料
},
// 取消
cancelItem(item) {
item.readonly = !item.readonly;//切換文本框的讀寫狀态
this.$nextTick(() =>{
Object.assign(this.desserts[this.editedIndex], this.editedItem);//點選取消之後,把未修改之前的資料還原到desserts數組
this.editedIndex = -1;//把索引标志置空
})
},
}
})
};
</script>
當然了,所有的資料操作最終還是要調接口的(如删除以及修改之後的儲存)