- 创建一个Vue组件,用于展示可编辑表格。在模板中使用
v-for指令来循环渲染表格的行和列,并使用v-model指令来绑定每个单元格的数据。
<template>
<table>
<tr v-for="(row, index) in tableData" :key="index">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">
<input v-model="cell.value" @change="updateCell(index, cellIndex)">
</td>
</tr>
</table>
</template>
- 在Vue组件的
data选项中定义表格数据tableData,并在created钩子函数中从后端获取初始数据。
<script>
export default {
data() {
return {
tableData: [],
};
},
created() {
this.fetchData();
},
methods: {
fetchData() {
axios.get('/api/data')
.then(response => {
this.tableData = response.data;
})
.catch(error => {
console.error(error);
});
},
updateCell(rowIndex, cellIndex) {
const newValue = this.tableData[rowIndex][cellIndex].value;
axios.post('/api/update', { rowIndex, cellIndex, newValue })
.then(response => {
console.log('Data uploaded successfully');
})
.catch(error => {
console.error(error);
});
},
},
};
</script>