Vue.js火速上手第十二章——子父通信

一、定义全局组件

   定义两个全局组件,呈现父子关系

Vue.component('balance', {
	template:`
	
你的余额不足
`, }); Vue.component('show',{ template: ` `, });
	

二、给子组件添加事件

     绑定on_click事件,并向父组件传递show-balance事件及{a:1,b:2}数据

Vue.component('show',{
	template:
	`
	
	`,
	methods:{
		on_click:function(){
			this.$emit('show-balance',{a:1,b:2});
		}
	},
});

三、父组件接收事件

 父组件接收子组件传来的show-balance事件,并定义show_balance来响应

Vue.component('balance', {
	template:`
	
余额不足
`, methods:{ show_balance:function(){ this.show=true; } }, data: function(){ return{ show:false, } }, });

效果展示:

Vue.js火速上手第十二章——子父通信_第1张图片

四、在父组件中接收子组件传递来的数据

	methods:{
		show_balance:function(data){
			this.show=true;
			console.log(data);
		}
	},

Vue.js火速上手第十二章——子父通信_第2张图片

 

五、本篇完整代码

index.html


	
		 
		chapter-18.11
	
			
		

 main.js

Vue.component('balance', {
	template:`
	
余额不足
`, methods:{ show_balance:function(data){ this.show=true; console.log(data); } }, data: function(){ return{ show:false, } }, }); Vue.component('show',{ template: ` `, methods:{ on_click:function(){ this.$emit('show-balance',{a:1,b:2}); } }, }); new Vue({ el: '#app', data:{ url:'http://www.baidu.com', }, methods:{ }, });

 

你可能感兴趣的:(Vue.js)