将心比心,方得人心~

vue 2 实现兄弟组件之间的通信

周洲 2017-12-18 16:05:07

第一步:在common->js目录新建一个名叫bus.js的文件

在bus.js里写入以下代码:


import Vue from 'vue'
export default new Vue()
第二步:在ratingselect->ratingselect.vue(兄弟组件)做如下操作:



1.script标签里引入bus.js import Bus from '@/common/js/bus.js'

2.在methods方法里写入以下代码:

	    methods: {
	    	select(type, event) {
	    		if (!event._constructed) {
	    			return
	    		}
                      // 注意慕课网讲师写的this.selectType = type 这段代码不要写了
	    		Bus.$emit('select', type)
	    	},
	    	toggleContent(event) {
	    		if (!event._constructed) {
	    			return
	    		}
                     // 注意慕课网讲师写的this.onlyContent = !this.onlyContent 这段代码不要写了
                     Bus.$emit('content', !this.onlyContent)
	    	}
	    }
第三步:food->food.vue中操作:



1.script标签里引入bus.js import Bus from '@/common/js/bus.js'

2.

               mounted() {
			Bus.$on('select', (msg) => {
			   this.selectType = msg
			   	this.$nextTick(() => {
					this.scroll.refresh()
				})
			 })
			Bus.$on('content', (msg) => {
			    this.onlyContent = msg
			    this.$nextTick(() => {
					this.scroll.refresh()
			    })
			})
		},



你也可以参考这篇文章瞧瞧:

https://www.cnblogs.com/place-J-P/p/7586819.html












打赏

『微信打赏』

Tag标签vue2 

我是有底线的