Vue父子组件传数据

父向子:props

子向父:$emit()

举个列子:

<div id="root">
	<div>
		<input type="text" v-model="inputval" @keyup.13="hadsubmit">
	</div>
    <ul>
    	<todo v-for="(item,index) of arr" :key="index" :content="item" :index="index" @delete="haddelete"></todo>
    </ul>
</div>

<script>
	Vue.component('todo',{
		props:['content','index'],
		template:'<li @click="dele">{{content}}</li>',
		methods:{
			dele:function(){
				this.$emit("delete",this.index)
			}
		}
	})
	new Vue({
		el:'#root',
		data:{
			inputval:'',
			arr:[]
		},
		methods:{
            hadsubmit:function(){
		   this.arr.push(this.inputval);
		   this.inputval=""
	},
	        haddelete:function(index){
              this.arr.splice(index,1)                     
 }
		}
	})
</script
大概的逻辑过程:
(1):父组件通过props向子组件传值 子组件获得父组件传来的内容和索引。
(2):子组件通过$emit()向父组件抛出触发事件名称(delete)和触发事件的list索引值。

(3):父组件通过监听对应事件名称(@delete)触发函数handleDelete。函数通过子组件抛出的索引值对应删除list


猜你喜欢

转载自blog.csdn.net/Q846169253/article/details/80324927
今日推荐