欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在 Vue.js中優(yōu)雅地使用全局事件的方法

 更新時(shí)間:2019年02月01日 08:16:44   作者:全棧工程師的自我修養(yǎng)  
這篇文章主要介紹了在 Vue.js中優(yōu)雅地使用全局事件的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

Vue 2.0 版本中取消了 v1 中的 $broadcast 方法,因此要使用全局事件時(shí),不可避免地會使用到 event-bus 之類的方法,本文旨在提出一種不需要用到 event-bus 的全局事件使用方法。

主要思路是將事件全部綁定在 $root 上,并為所有全局事件添加一個(gè)前綴防止沖突,再通過向 $options 上注入新的 key 來簡化使用方式。

以下為 mixin 文件代碼

// event-mixin.js
export default {
 created() {
  if (this.$options.events) {
   Object.keys(this.$options.events).forEach(key => {
    let handler = this.$options.events[key]
    if (typeof handler === 'string') {
     handler = this[handler]
    }
    this[key + '::handler'] = handler.bind(this)
    this.$root.$on('global::' + key, this[key + '::handler'])
   })
  }
 },
 beforeDestroy() {
  if (this.$options.events) {
   Object.keys(this.$options.events).forEach(key => {
    this.$root.$off('global::' + key, this[key + '::handler'])
   })
  }
 }
}

使用前先在 main.js 中調(diào)用 mixin

Vue.mixin(require('./event-mixin.js').default)
在各個(gè)組件中,向 $root 發(fā)送事件即可

// a.vue
export default {
  name: 'a',
  events: {
    'evt.a': 'handlerA',
    'evt.b'() {
      console.log('B triggered')
    }
  },
  methods: {
    handlerA() {
      console.log('A triggered')
    }
  }
}

// b.vue
export default {
  name: 'b',
  events: {
    'evt.b'() {
      console.log('B triggered again')
    }
  }
}
// c.vue
export default {
  name: 'c',
  created() {
    this.$root.$emit('global::evt.a') // 'A triggered'
    this.$root.$emit('global::evt.b', 'data') // 'B triggered', 'B triggered again'
    // 使用以上方式觸發(fā),也可以在 mixin 中向?qū)嵗砑訉S糜|發(fā)方法
  }
}

使用這種方法,可以避免新建專門用于傳輸事件的 vue 實(shí)例,編寫回調(diào)函數(shù)時(shí)也更容易管理。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論