Vue子组件之间的传值
子组件之间用bus总线进行传值
- 第一种方法
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var bus = new Vue(); var app = new Vue( { el:"#d1", data:{name:"Vue", bus}, components:{ study:{ template:`<button v-on:click="touch">点我</button>`, methods:{ touch() { alert(666); bus.$emit("hahaha"); // touch方法触发 bus抛出hahaha信号 } } }, run:{template: `<p>{{num}}</p>`, data:function(){ return { num:0 } }, mounted:function () { console.log(this.num);
>>>>>>>>>>>>>>>>>>>>>>>>>> this指的是对应的 run组件 var _this = this;
>>>>>>>>>>>>>>>>>>>>>>>>>bus捕捉“hahaha”信号,执行对应的函数方法 bus.$on("hahaha",function () { alert("笑嘻嘻美滋滋"); _this.num +=1; }) } } } } ) </script>
htmlbody中
<body> <div id="d1"> <study></study> #两个子组件 <run></run> </div> </body>
- 第二种方法:
直接将bus实例对象注到根vue对象data中。
var app= new Vue({
el:'#app',
data:{
bus
}
})
在子组件中通过this.$root.Bus.$on(),
this.$root.Bus.$emit() 来调用
浙公网安备 33010602011771号