刚发完Vue.js(2)----常用指令,做个实例巩固一下,来实现对数组的增加和删除的效果。
样式就省略不说,感兴趣的可以评论。
首先实现输入框,下拉框和提交,实现增加人员信息功能。
姓名: 年龄: 性别:
@click 是 v-on:click的缩写形式,当点击提交按钮时,触发的是createUser()函数
createUser:function () { this.users.push(this.newUser); this.newUser = {name:'',age:0,sex:'Male'}
}下面是三组原始数据:
| 姓名 | 年龄 | 性别 | 删除 |
| {{user.name}} | {{user.age}} | {{user.sex}} |
原始数据存储在model层,如下:
new Vue({
el:"#view",
data:{
newUser:{
name:'',
age:0,
sex:'男'
},
users:[
{
name:'王临风',
age:20,
sex:'男'
},{
name:"王顽皮",
age:20,
sex:'女'
},{
name:"卢大美",
age:20,
sex:'女'
}
]
},点击删除按钮,调用deleteUser()函数,为了能够删除指定的数组元素,所以在遍历users查找user时,应该同时给每一个元素一个特定的参数。v-for=('user,index') in users,这样在执行 deleteUser()时就可以将index作为参数代入到函数中。
deleteUser:function(index){ console.log(index); this.users.splice(index,1);
}splice(index,num,item)方法是删除数组中指定位置的元素,第一个参数是指定从数组中的哪个位置开始删除元素,第二个参数是指定删除几个元素。第三个参数是可以向数组添加元素,并返回新的数组。
好啦,逐步分析如上。有建议或疑问可以发在评论中哦!如果看到了这里,记得点个喜欢哦!每一个人的支持对我都是莫大的鼓励!下面放一个全部的代码:
添加删除信息 fieldset{ display: block; border: 1px solid #bcbcbc; width: 50%; margin: 0 auto; padding: 15px; } legend{ font-size: 8px; } input{ height: 20px; } select{ width: 60px; } button{ border: none; background:#009A61; color:white; width:70px; border: 1px solid #009A61; border-radius: 4px; margin-left: 20px; line-height: 20px; } table{ margin-top: 40px; width: 100%; text-align: center; border-collapse:collapse; } thead,td,tr{ border: 1px solid #bcbcbc; line-height: 35px; } thead td{ background: #009A61; color: white; }
作者:_地中海大叔
链接:https://www.jianshu.com/p/04c253b4798e



