vue父子组件通信demo

by zhoou changhong

HTML

<div id="zj">
	<v-parent></v-parent>
</div>

<template id="parent">
	<div>
		表单内容:{{test}}<br>
		计数:{{n}}<br>
		<input type="text" v-model='test'>
		<v-child  :message='test' v-on:kkk='parentFun'></v-child>	
	</div>
</template>

<template id="child">
	<button v-on:click="childFun">{{num}}</button>
</template>

JavaScript

var zj=new Vue({
	el:'#zj',
	components:{
		'v-parent':{//局部注册父组件
			template:'#parent',
			data:function(){
				return {
					test:'初始值',//test的值由父组件模板中的input动态双向绑定
					n:0//测试子组件传递的数据,如果变化则传递成功
				};
			},
			methods:{
				parentFun:function(a){//测试子组件通过$emit传递过来的参数
					this.n=a;
				}
			},
			components:{
				'v-child':{//局部注册子组件
					props:['message'],//定义一个变量接收父组件传递过来的数据,指向父组件的test值,并且会跟随input中输入的内容实时变化
					template:'#child',
					data:function(){
						return {num:0};//测试子组件单机事件
					},
					methods:{
						childFun:function(){
							//子组件方法,每单机一次数值加1,通过参数'kkk'把子组件处理之后的数据'num'传递出去,由父组件的方法接收并显示
							this.num++;
							this.$emit('kkk',this.num);
						}	
					}
				}
			}
		}
	}
});