Vue 組件間傳值、通信

父組件 => 子組件
  • props
// 父組件
<Child title='I am Child'/>

// 子組件
props: { title: String }
  • refs
// 父組件
<Child ref='child'/>
...
this.$refs.child.xxx
子組件 => 父組件
  • 自定義事件
// 父組件
<Child @say='handleSay'/>
...
handleSay(val) {
 console.log(val) // hello
}

// 子組件
this.$emit('say', 'hello')
兄弟組件
  • 通過(guò)共同的祖輩組件搭橋,$parent 或 $root
// 兄弟1
this.$parent.$on('say', handleSay)

// 兄弟2
this.$parent.$emit('say', 'hello')
祖先 => 后代
  • provide&inject 傳值
// 祖先
provide() {
  return { msg: 'hello world'}
}

// 后代
<span>{{ msg }}</span>
...
inject: ['msg']
  • broadcast 通信
// 定義broadcast方法,指定派發(fā)事件名稱和數(shù)據(jù)
function broadcast(eventName, data) {
  this.$children.forEach(child => {
    // 子組件出發(fā)$emit
    child.$emit(eventName, data)
    if(child.$children.length) {
      // 遞歸調(diào)用,通過(guò)call修改this指向child
      broadcast.call(child, eventName, data)
    }
  }
}
Vue.prototype.$broadcast = function (eventName, data) {
  broadcast.call(this, eventName, data)
}
后代 => 祖先
  • dispatch
// 定義dispatch方法,指定派發(fā)事件名稱和數(shù)據(jù)
function dispatch(eventName, data) {
  let parent = this.$parent
  // 遞歸查找父元素
  while(parent) {
    // 父元素調(diào)用$emit出發(fā)事件
    parent.$emit('say', 'hello')
    parent = parent.$parent
  }
}
Vue.prototype.$dispatch = dispatch

// Child.vue
<h1 @click='dispatch("say", "hello")'>{{ msg }}</h1>

// App.vue
this.$on('say', this.handleSay)
任意組件間
  • 事件總線:創(chuàng)建一個(gè)Bus類負(fù)責(zé)事件派發(fā)、監(jiān)聽(tīng)和回調(diào)管理(也可直接創(chuàng)建一個(gè)Vue實(shí)例,直接使用$on和$emit)
// Bus:事件派發(fā)、監(jiān)聽(tīng)和回調(diào)管理
class Bus {
  constructor() {
    this.callbacks = {}
  }
  $on(name, fn) {
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
  }
  $emit(name, args) {
    if(this.callbacks[name]) {
      this.callbacks[name].forEach(cb => cb(args))
    }
  }
}

// main.js
Vue.prototype.$bus = new Bus() // 也可用 new Vue()

// 組件1
this.$bus.$on('say', this.handleSay)
// 組件2
this.$bus.$emit('say', 'hello')
  • vuex:創(chuàng)建唯一的全局?jǐn)?shù)據(jù)管理者store,通過(guò)他管理數(shù)據(jù)并通知組件狀態(tài)變更
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容