非父子组件之间的传值

组件的组织

组件系统是 Vue 的另一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用。仔细想想,几乎任意类型的应用界面都可以抽象为一个组件树:

为了能在模板中使用,这些组件必须先注册以便 Vue 能够识别。这里有两种组件的注册类型:全局注册局部注册。Vue.component 全局注册:

1
2
3
Vue.component('component-name', {
// ... options ...
})

前面我们谈到可以通过emit来实现下层对上层的事件传递,但这样对于复杂的结构来使用会显 得很麻烦

Vue总线机制

下面通过一个例子来讲解如何使用Vue总线机制解决非父子组件间的传值问题

首先代码如上,两个child子组件属于非父子组件。我想实现一个功能:当我点击某个字符串时所有元素都变为相同字符串。

1
2
Vue.prototype.bus=new Vue() 
//在Vue的原型类上挂载bus属性,这样每一个Vue创建的实例都会有bus属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 <body>
<div id="app">
<child content="zhang"></child>
<child content="jin"></child>
</div>
<script>
Vue.prototype.bus=new Vue()
Vue.component('child',{
data:function(){
return{
number:this.content
}
},
props:{
content:String
},
template:'<div @click="handleclick">{{number}}</div>',
methods:{
handleclick:function(){
this.bus.$emit('change',this.number)
}
},
//每个组件都有生命周期钩子,组件在挂载时会执行的函数
mounted:function(){
let that=this
//监听bus的改变,因为bus是Vue的实例,所以会有$on方法,可监听到bus触发的change事件,再执行函数
this.bus.$on('change',function(res){
that.number=res
})
}
})
var vm=new Vue({
el:'#app'
})
</script>
</body>

每个 Vue 实例都实现了事件接口(Events interface),即:

使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件

给组件绑定原生事件

有时候,你可能想在某个组件的根元素上监听一个原生事件。可以使用 .native 修饰 v-on 。例如:

1
<child @click.native="handle" ></child>

总结

在Vue的原型类上挂载bus属性

1
Vue.prototype.bus = new Vue()

触发组件 A 中的事件,content是暴露出去的值

1
bus.$emit('change', content)

在其他(这里是所有)组件创建的钩子中监听事件,res是获取的值

1
2
3
bus.$on('change', function (res) {
console.log(res)
})

请我喝杯咖啡吧~

支付宝
微信