用vue实现表格的增删查改,可显示序号、姓名、年龄
(1)使用id选择器
<div id="app">
<table border="1" cellspacing="0"cellpadding="20">
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作|<button @click="addHero">新增</button></th>
</tr>
<tr v-for="hero in heroList">
<td>{{hero.id}}</td>
<td>{{hero.name}}</td>
<td>{{hero.age}}</td>
<td><button @click="deleteHero(hero.id)">删除</button>|<button>修改</button></td>
</tr>
</table>
<div v-show="isInputShow">
<h3>新增英雄</h3>
<input type="text" v-model="hero.id"placeholder="请输入序号"><br><br>
<input type="text" v-model="hero.name"placeholder="请输入姓名"><br><br>
<input type="number" v-model="hero.age"placeholder="请输入年龄"><br><br>
<input type="submit" @click="insertHero"><br><br>
</div>
</div>
(2)创建vue案例,并实现部分功能
<script>
new Vue({
el:'#app',
data:{
//控制表单隐藏和显示
isInputShow:false,
//双向绑定实现表单的获取
hero:{
id:'',
name:'',
age:'',
},
heroList:[
{id:1,name:'曹操',age:36},
{id:2,name:'刘备',age:32},
{id:3,name:'孙权',age:28},
]
},
methods: {
deleteHero(id) {
//alert(id)
this.heroList = this.heroList.filter((e, i) => {
return e.id != id/*不等于id的就留下来,等于id的就删掉*/
})
},
addHero(){
this.isInputShow=!this.isInputShow
},
insertHero() {
console.log(this.hero)
this.heroList.push(this.hero)
}
}
})
</script>
(3)完整代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue表格案例</title>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<table border="1" cellspacing="0"cellpadding="20">
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作|<button @click="addHero">新增</button></th>
</tr>
<tr v-for="hero in heroList">
<td>{{hero.id}}</td>
<td>{{hero.name}}</td>
<td>{{hero.age}}</td>
<td><button @click="deleteHero(hero.id)">删除</button>|<button>修改</button></td>
</tr>
</table>
<div v-show="isInputShow">
<h3>新增英雄</h3>
<input type="text" v-model="hero.id"placeholder="请输入序号"><br><br>
<input type="text" v-model="hero.name"placeholder="请输入姓名"><br><br>
<input type="number" v-model="hero.age"placeholder="请输入年龄"><br><br>
<input type="submit" @click="insertHero"><br><br>
</div>
</div>
</body>
<script>
new Vue({
el:'#app',
data:{
//控制表单隐藏和显示
isInputShow:false,
//双向绑定实现表单的获取
hero:{
id:'',
name:'',
age:'',
},
heroList:[
{id:1,name:'曹操',age:36},
{id:2,name:'刘备',age:32},
{id:3,name:'孙权',age:28},
]
},
methods: {
deleteHero(id) {
//alert(id)
this.heroList = this.heroList.filter((e, i) => {
return e.id != id/*不等于id的就留下来,等于id的就删掉*/
})
},
addHero(){
this.isInputShow=!this.isInputShow
},
insertHero() {
console.log(this.hero)
this.heroList.push(this.hero)
}
}
})
</script>
</html>
(4)运行结果如下(注意:点击新增后才会有新增的页面)