Vue3 实现表格的增加和删除

369 阅读1分钟
<template>
  <p><input type="text" placeholder="请输入用户名" v-model="obj.name" /></p>
  <p><input type="text" placeholder="请输入年龄" v-model="obj.age" /></p>
  <button @click="add">添加</button>
  <table border="1">
    <tr>
      <th>用户名</th>
      <th>年龄</th>
      <th>操作</th>
    </tr>
    <tr v-for="(item, index) in list" :key="index">
      <td>{{ item.name }}</td>
      <td>{{ item.age }}</td>
      <td><button @click="del(index)">删除</button></td>
    </tr>
  </table>
</template>

<script setup>
import { reactive, ref } from "vue";

let list = reactive([]);
let obj = reactive({
  name: "",
  age: "",
});
const add = () => {
  if (obj.name.trim() == "" || obj.age.trim() == "") {
    return;
  }
  // 实现深拷贝的两种方式
  // list.push(JSON.parse(JSON.stringify(obj)));
  // list.push({...obj})
  // 下面的写法 等于 上面拓展运算符的写法
  list.push({
    name: obj.name,
    age: obj.age,
  });
  for (var key in obj) {
    obj[key] = "";
  }
};
const del = (index) => {
  list.splice(index, 1);
};
</script>