1.不使用组件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例 - vue实现列表增加和删除</title> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> </head> <body> <div> <input v-model="newAddText" placeholder="请输入要添加的内容" /> <button @click='addNewList'>添加</button> <ul> <li v-for='(list,index) in lists' v-bind:key='list.id'> {{list.title}} <button v-on:click='lists.splice(index, 1)'>删除</button> </li> </ul> </div> <script> var vm = new Vue({ el: '#app', data: { newAddText:'', lists:[ {id:1,title:'手机号码'}, {id:2,title:'qq号'}, {id:3,title:'姓名'}, ], nextTodoId: 4 }, methods:{ addNewList:function(){ this.lists.push({ id:this.nextTodoId++, title:this.newAddText }) this.newAddText='' } } }) </script> </body> </html>
初始界面:
添加一个列表:
删除一个列表:
2.使用组件方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例 - vue实现列表增加和删除</title> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> </head> <body> <div> <input v-model="newAddText" placeholder="请输入要添加的内容" /> <button @click='addNewList'>添加</button> <ul> <li is='list-item' v-for='(list,index) in lists' v-bind:key='list.id' v-bind:title='list.title' v-on:remove='lists.splice(index,1)'> </li> </ul> </div> <script> Vue.component('list-item', { template: '\ <li>\ {{ title }}\ <button v-on:click="$emit(\'remove\')">删除</button>\ </li>\ ', props: ['title'] }) var vm = new Vue({ el: '#app', data: { newAddText:'', lists:[ {id:1,title:'手机号码'}, {id:2,title:'qq号'}, {id:3,title:'姓名'}, ], nextTodoId: 4 }, methods:{ addNewList:function(){ this.lists.push({ id:this.nextTodoId++, title:this.newAddText }) this.newAddText='' } } }) </script> </body> </html>
效果跟上面的一样的!
以上这篇Vue 实现列表动态添加和删除的两种方法小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: