详解vue添加删除元素的方法

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue实例:添加删除元素r</title> <style type="text/css"> .form-group{ margin:10px; } .form-group>label{ display: inline-block; width: 5rem; text-align: right; } </style> </head> <body> <div> <div> <label>name:</label> <input type="text" v-model='newitems.name'> </div> <div> <label>age:</label> <input type="text" v-model='newitems.age'> </div> <div> <label>sex:</label> <select v-model='newitems.sex'> <option value="男">男</option> <option value="女">女</option> </select> </div> <div> <label></label> <button v-on:click = 'addPerson'>Create</button> </div> <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>Sex</th> <th>Delete</th> </tr> </thead> <tbody> <tr v-for="item in items"><!--v-for--> <td>{{item.name}}</td> <td>{{item.age}}</td> <td>{{item.sex}}</td> <td><button @click="deletePerson($index)">Delete</button></td> </tr> </tbody> </table> </div> </body> <script src="https://www.jb51.net/article/vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el:'#app', data:{ newitems:{ name:'', age:'18', sex:'女' },//newitems默认的 items:[{ name:'lily', age:18, sex:'女' },{ name:'lily', age:18, sex:'女' },{ name:'lily', age:18, sex:'女' },{ name:'lily', age:18, sex:'女' },{ name:'lily', age:18, sex:'女' }] }, methods:{ addPerson:function(){ this.items.push(this.newitems)//往items中添加newitems this.newitems = {name:'',age:'18',sex:'女'} },//添加元素 deletePerson: function(index){ // 删一个数组元素 this.items.splice(index,1); } } }) </script> </html>

大家可以测试以下,感谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/df2f471140ed291914d9e5a493443171.html