Vue如何实现组件通信?

Vue组件通信的三种情况:

  • 父子通信
  • 爷孙通信
  • 兄弟通信
  1. 父子通信:父组件使用Prop向子组件传递数据,子组件通过事件向父组件发送消息,使用 v-on 绑定自定义事件)

    {{message}}

    Vue.component('child',{ template: `
    我是儿子
    ` }) new Vue({ el: '#app', data: { message: 'hello', visible: false } })
  2. 爷孙通信(通过两对父子通信,爷爸之间父子通信,爸儿之间父子通信)

    {{message}}

    Vue.component('child',{ props: ['seen','seensunzi'], template: `
    我是爸爸
    ` }) Vue.component('sunzi',{ props: ['seensunzi'], template: `
    我是儿子
    ` }) var vue = new Vue({ el: '#app', data: { message: '我是爷爷', seen: false, seensunzi: false }, methods:{ log(seen){ console.log('爷爷收到消息:爷爷先关掉儿子,再关掉我爸爸') setTimeout(()=>{ this.seen = false },2000) } } })
  3. 兄弟通信(new Vue() 作为 eventBus)
    let eventHub = new Vue() Vue.prototype.$eventHub = eventHub Vue.component('component-a',{ template:`
    a
    `, methods:{ notify(){ this.__proto__ === Vue.prototype this.$eventHub.$emit('xxx','hi') } } }) Vue.component('component-b',{ template:`
    b
    `, created(){ this.$eventHub.$on('xxx',(data)=>{ this.$refs.output.textContent = data }) } }) let app = new Vue({ el: "#app" })

你可能感兴趣的:(Vue如何实现组件通信?)