vue3实现表格的数据增加和删除
主页:
<template>
<div>
<p>用户名:<input type="text" v-model="obj.name" /></p>
<p>年龄:<input type="text" v-model="obj.age" /></p>
<p>个人描述:<input type="text" v-model="obj.dec" /></p>
<button @click="add">添加</button>
</div>
<table border="1">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>个人描述</th>
<th>操作</th>
</tr>
<tr v-for="(v, i) in arr" :key="i">
<td>{{ v.name }}</td>
<td>{{ v.age }}</td>
<td>{{ v.dec }}</td>
<td><button @click="del(i)">删除</button></td>
</tr>
</table>
</template>
<script setup>
/* setup 语法糖
不需要return一个对象了 */
import { reactive, onMounted } from "vue";
onMounted(() => {
console.log("onMounted");
});
const obj = reactive({
name: "",
age: "",
dec: "",
});
const arr = reactive([]);
const add = () => {
if(obj.name.trim()==''||obj.age.trim()==''||obj.dec.trim()==''){
return
}
/* 实现深拷贝的两种方式 */
// arr.push( JSON.parse(JSON.stringify(obj)) )
// arr.push( {...obj} )
/* 和上面拓展运算符的写法 画等于号 */
arr.push({
name:obj.name,
age:obj.age,
dec:obj.dec,
})
// obj.name = ''
// obj.age = ''
// obj.dec = ''
/* 和上面手动置空的方法 画等于号 */
for(var key in obj){
obj[key] = ''
}
};
function del(i){
arr.splice(i,1)
}
</script>
<style scoped>
td,
th {
padding: 10px;
}
</style>