vue3实现可编辑表格(与后端对接版)

346 阅读1分钟
  1. 创建一个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>
  1. 在Vue组件的data选项中定义表格数据tableData,并在created钩子函数中从后端获取初始数据。
<script>
export default {
  data() {
    return {
      tableData: [],
    };
  },
  created() {
    // 调用后端接口获取初始数据
    this.fetchData();
  },
  methods: {
    fetchData() {
      // 调用后端接口获取数据
      // 示例:使用axios发送GET请求
      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请求
      axios.post('/api/update', { rowIndex, cellIndex, newValue })
        .then(response => {
          console.log('Data uploaded successfully');
        })
        .catch(error => {
          console.error(error);
        });
    },
  },
};
</script>