下面将介绍两种方式实现动态添加和删除列表

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 id="app">
 <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 id="app">
 <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>

效果跟上面的一样的!

Logo

前往低代码交流专区

更多推荐