用到了 v-model @click v-show v-for 數組常用API
核心 v-model 雙向進行數據綁定
<template>
<div>
<div>
<input type="text" placeholder="發布" v-model="obj.user" />
<input type="text" placeholder="年齡" v-model="obj.age" />
<input type="text" placeholder="性別" v-model="obj.sex" />
<span>
<button @click="add()">增加</button>
</span>
</div>
<table>
<thead>
<tr>
<td>序列號</td>
<td>姓名</td>
<td>年齡</td>
<td>性別</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in titles" :key="index">
<td>{{item.id}}</td>
<td>{{item.user}}</td>
<td>{{item.age}}</td>
<td>{{item.sex}}</td>
<td>
<span class="edit" @click="editData(item)">編輯</span>
<span class="delete" @click="del(index)">刪除</span>
</td>
</tr>
</tbody>
</table>
<div class="layer" v-show="flag">
<div class="mask">
<div class="title">
編輯
<span>x</span>
</div>
<div class="content">
<input type="text" placeholder="發布" v-model="edit.user" />
<input type="text" placeholder="年齡" v-model="edit.age" />
<input type="text" placeholder="性別" v-model="edit.sex" />
<button @click="updata()">更新</button>
<button @click="flag=false">取消</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
find: "find",
flag: false,
obj: {
user: "",
age: "",
sex: "",
id: ""
},
titles: [
{
user: "wxy",
age: "18",
sex: "0",
id: "01"
},
{
user: "wxy2",
age: "20",
sex: "0",
id: "02"
},
{
user: "wxy3",
age: "19",
sex: "1",
id: "03"
}
],
edit: {}
};
},
methods: {
add() {
//增加數據
//動態id
var _id =
Math.max.apply(
null,
this.titles.map(v => {
return v.id;
})
) + 1;
//判斷增加數據是否全部為空
if (!this.obj.user || !this.obj.age || !this.obj.sex) return;
//將添加的數據,增加到數組中
this.titles.push({
user: this.obj.user,
age: this.obj.age,
sex: this.obj.sex,
id: _id
});
//添加完成后,將輸入框清空
this.obj = {
user: "",
age: "",
sex: "",
id: ""
};
},
//刪除數據
del(index) {
//點擊刪除后,將刪除數據的下標傳入,進行刪除
this.titles.splice(index, 1);
},
//編輯數據
editData(item) {
//將要編輯的數據傳入
//編輯層打開,顯示
this.flag = true;
//將要編輯的數據賦值給this.edit,綁定this.edit
this.edit = {
user: item.user,
age: item.age,
sex: item.sex,
id: item.id
};
},
//更新數據
updata() {
//點擊更新按鈕后觸發,將用對象中的ID值來判斷,選中更改的對象,並將更改后的對象重新給到this.titles
for (var i = 0; i < this.titles.length; i++) {
if (this.titles[i].id == this.edit.id) {
this.titles[i] = this.edit;
this.flag = false;
}
}
}
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
table {
margin: auto;
border-collapse: collapse;
}
table td {
border: 1px solid black;
}
</style>
