Several ways to pass values
- Sons (downward) by value : The property
- Child-parent (up) by value : through custom event
- Non-traditional values Sons : By Bus (non-parent-child value one pass mode)
Non Sons pass values bus
Also known as bus
Objective: dissemination of information through the sub-assembly, the parent Subscribers receive
- Subassemblies announcement parent is not acceptable, as the paper version of the newspaper, you always have a posted limit areas, such as Henan Daily to publish only the same, not the same as to other parts of the circulation in Henan, while the bus is to Henan Daily the next level, it becomes a national daily newspaper, issued in the country
This case used in the publication ($ emit) and subscriptions ($ on) Publish and Subscribe introduction
Code Description show:
/*-----------------------html-----------------------------*/
<div id="root">
<My></My>
</div>
/*-----------------------js-----------------------------*/
const bus = new Vue(); // 公共汽车
//通过new Vue()实例化出来一个对象
new Vue({
el:"#root",
data:{
age:13,
},
components:{
My:{
methods:{
fn(){
bus.$emit("my",2); //现在 $emit 是在 bus 这个实例下了 *****
}
},
template:`
<div>My
<input type="button" @click="fn" value="发布">
</div>
`
}
},
mounted(){
bus.$on("my",()=>{ //这个 $on 也是在 bus 这个实例下了,那么当发布者发布的时候,订阅者就能收到了
console.log(1111111111);
})
}
})
to sum up
I would like a new instance of a Vue () Object
to $ emit and $ on in the same instance of the object below
so that no matter when my $ on $ emit and in what places have access to and released