实现以下需求:
需求1: 铺设页面, 准备初始的数据(自己手写数据结构)
需求2: 当输入框没有值, 要给用户一个提示, 必须都有值才能增加新数据
需求3: 添加功能 - 想好数据结构统一对象的key
需求4: 点击编辑功能, 把值赋予到输入框上(不要操作dom, 数据驱动页面)
需求5: 用户修改后, 点击相同按钮 - 实现编辑后更新页面效果
需求6: 点击删除, 删除这行数据
<template>
<div id="app">
<div>
<span>姓名:</span>
<input type="text" v-model="name" />
</div>
<div>
<span>年龄:</span>
<input type="number" v-model.number="age" />
</div>
<div>
<span>性别:</span>
<select v-model="sex">
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<div>
<button @click="addFn">添加/修改</button>
</div>
<div>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
<tr v-for="(obj, index) in arr" :key="obj.id">
<td>{
{
index + 1 }}</td>
<td>{
{
obj.name }}</td>
<td>{
{
obj.age }}</td>
<td>{
{
obj.gender }}</td>
<td>
<button @click="delFn(index)">删除</button>
<button @click="editFn(index)">编辑</button>
</td>
</tr>
</table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
name: "",
age: 0,
sex: "",
arr: [
{
id: 1, name: "Tom", age: 19, gender: "男" },
{
id: 2, name: "Jone", age: 21, gender: "女" },
],
selectIndex: "",
flag: false,
};
},
methods: {
addFn() {
if (this.name.length === 0 || this.age.length === 0) {
alert("内容不能为空");
return;
}
// let id = this.arr.length > 0 ? this.arr[this.arr.length - 1].id + 1 : 1;
if (!this.flag) {
this.arr.push({
// id: id,
name: this.name,
age: this.age,
gender: this.sex,
});
} else {
this.arr.splice(this.selectIndex, 1, {
name: this.name,
age: this.age,
gender: this.sex,
});
this.flag = false;
}
this.name = "";
this.age = 0;
this.sex = "";
},
editFn(i) {
this.name = this.arr[i].name;
this.age = this.arr[i].age;
this.sex = this.arr[i].gender;
this.selectIndex = this.arr.findIndex((obj) => obj.id === i + 1);
this.flag = true;
},
delFn(ind) {
this.arr.splice(ind, 1);
},
},
};
</script>
上面代码可实现以上需求,效果图如下所示
注意:以上vue代码是基于是Vue官方提供的一个全局模块包@vue/cli(得到vue命令),从而创建脚手架项目,还使用了webpack打包工具,使用时注意把第三方包下载完整