非父子组件传值

我心飞翔 分类:vue

# 非父子组件间传值

当组件的嵌套多时,非父子组件间传值就显得复杂,除了使用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>

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

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

HTML

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

JS

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) => {
      this.childVal = msg
    })
  }
})

var vm = new Vue({
  el: '#root'
})

回复

我来回复
  • 暂无回复内容