vue组件之间的通讯。
上一篇博客写了一个点击按钮之后弹出信息的组件。这次对弹出的信息做一下手脚。
html
<div id="seg1"> <alert msg="Yhooo"></alert>< -- 通过msg绑定我们需要的信息 -- > </div>
js
var Alert={ template:'<button @click="on_click">弹弹弹</button>', props:['msg'],//props用来接受父组件的数据,可以是对象或数组。 methods:{ on_click:function(){ alert(this.msg); } } }; new Vue({ el: '#seg1', components:{ alert:Alert } });
vue组件父与子通讯小实例——显示余额
html
<div id="app"> <balance></balance> </div>
js
Vue.component('balance',{ template:'<div><show @show-balance="show_balance"></show><div v-if="show">您的余额为8元</div></div>', methods:{ show_balance:function(data){ console.log('data',data);//用来检测通讯是否成功 this.show=true;//点击后改变状态 } }, data:function(){ return{ show:false,//默认隐藏 } } }); Vue.component('show',{ template:'<button @click="on_click()">显示余额</button>', methods:{ on_click:function(){ this.$emit('show-balance',{a:1,b:2}) } } }); new Vue({ el: '#app', });
vue组件兄弟间通讯实例
html
<div id="app">
<huahua></huahua>
<huhu></huhu>
</div>
js
var Event=new Vue(); Vue.component('huahua',{ template:'<div>我说:<input @keyup="on_change" v-model="say"/></div>', data:function(){ return{ say:'', } }, methods:{ on_change:function(){ Event.$emit('huahua-say-something',this.say); } } }) Vue.component('huhu',{ template:'<div>花花说:{{huahua_say}}</div>', data:function(){ return{ huahua_say:'', }; }, mounted:function(){ var me=this; Event.$on('huahua-say-something',function(data){ me.huahua_say=data; }) } }) new Vue({ el:"#app", })