非父子组件传值

# 非父子组件间传值

当组件的嵌套多时,非父子组件间传值就显得复杂,除了使用vuex (opens new window)实现之外,还可以通过Bus(或者叫 总线/发布订阅模式/观察者模式)的方式实现非父子组件间传值。

<div id="root">
    <child1 content="组件1:点我传出值"></child1>
    <child2 content="组件2"></child2>
</div>

<script type="text/javascript">
	Vue.prototype.bus = new Vue()
	// 每个Vue原型上都会有bus属性,而且指向同一个Vue实例

	Vue.component('child1', {
		props: {
			content: String
		},
		template: '<button @click="handleClick">{{content}}</button>',
		methods: {
			handleClick(){
				this.bus.$emit('change', '我是组件1过来的~') // 触发change事件,传出值
			}
		}
	})

	Vue.component('child2', {
		data() {
			return {
				childVal: ''
			}
		},
		props: {
			content: String,
		},
		template: '<button>{{content}} + {{childVal}}</button>',
		mounted() {
			this.bus.$on('change', (msg) => { // 绑定change事件,执行函数接收值
				this.childVal = msg
			})
		}
	})

	var vm = new Vue({
		el: '#root'
	})
</script>
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
37
38
39
40
41
42

上面代码中,在Vue原型上绑定一个bus属性,指向一个Vue实例,之后每个Vue实例都会有一个bus属性。

此方法传值,不限于兄弟组件之间,其他关系组件间都适用。

See the Pen 非父子组件间传值2(Bus /总线/发布订阅模式/观察者模式) by xugaoyi (@xugaoyi) on CodePen.

上次更新: 2023/07/11, 15:43:07
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>