vuepress-theme-vdoing/docs/《Vue》笔记/02.组件/65.非父子组件传值.md

2.4 KiB
Raw Blame History

title date permalink categories tags author
非父子组件传值 2020-02-15 14:55:03 /pages/d408e64f666f146d
《Vue》笔记
组件
null
name link
xugaoyi https://github.com/xugaoyi

非父子组件间传值

当组件的嵌套多时,非父子组件间传值就显得复杂,除了使用vuex实现之外还可以通过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>

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

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

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