前言
幾天前我們發(fā)布了《阿里媽媽又做了新工具,幫你把 Vue2 代碼改成 Vue3 的》,這篇文章分享一下其中一個轉(zhuǎn)換規(guī)則:eventHub(或稱為eventBus)的轉(zhuǎn)換的思路。
Vue 官方的遷移方案:https://v3.cn.vuejs.org/guide/migration/events-api.html
1. 先介紹下 eventHub
1.1 Vue2 的 eventHub
eventHub 是組件間共用的事件中心,在 Vue 中用來作為組件溝通的橋梁,向 eventHub 發(fā)送消息,其它模塊通過訂閱這個 eventHub 來獲取相應(yīng)的數(shù)據(jù)。
官網(wǎng)介紹:
Vue 實例可用于觸發(fā)由事件觸發(fā) API 通過指令式方式添加的處理函數(shù) (
off 和 $once)。
event hub,用來創(chuàng)建在整個應(yīng)用程序中可用的全局事件監(jiān)聽器的實現(xiàn):
// eventHub.js
const eventHub = new Vue()
export default eventHub
// ChildComponent.vue
import eventHub from './eventHub'
export default {
mounted() {
// 添加 eventHub 監(jiān)聽器
eventHub.$on('custom-event', () => {
console.log('Custom event triggered!')
})
},
beforeDestroy() {
// 移除 eventHub 監(jiān)聽器
eventHub.$off('custom-event')
}
}
1.2 Vue3中的 eventHub
然而在Vue 3中,官方移除$on、$off 和 $once 方法
我們從實例中完全移除了 $on、$off 和 $once 方法。$emit 仍然包含于現(xiàn)有的 API 中,因為它用于觸發(fā)由父組件聲明式添加的事件處理函數(shù)。
在 Vue 3 中,已經(jīng)不可能使用這些 API 從組件內(nèi)部監(jiān)聽組件自己發(fā)出的事件了,該用例暫沒有遷移的方法。
2.遷移方案
2.1 eventHub 三方庫的選擇
Vue官方提供了替代的方案:使用第三方庫,“eventHub 模式可以被替換為實現(xiàn)了事件觸發(fā)器接口的外部庫,例如 mitt 或 tiny-emitter”。研究了mitt 和 tiny-emitter,mitt 雖然 star 數(shù)更高,但是它不支持 $once 方法,需要使用其它方法組合實現(xiàn)。為了降低遷移成本,我選擇使用 tiny-emitter。
A tiny (less than 1k) event emitter library.
2.2 遷移工具的選擇
面對N多個項目,百八十個文件,各種 eventHub 的實現(xiàn)方式,手工替換肯定不是個可實現(xiàn)的解決方案。
更優(yōu)方案是基于 AST(抽象語法樹)解構(gòu)代碼,根據(jù)既定規(guī)則,批量修改然后輸出文件。
在此推薦 GoGoCode 這個處理AST強(qiáng)力好入手的工具
GoGoCode提供了類似JQuery的API,用以操作AST對象。降低了使用AST的門檻,幫助開發(fā)者從繁瑣的AST操作中解放出來
正是代碼遷移的最有力助手。
另外安利一個做AST分析離不開的工具:https://astexplorer.net,使用它我們可以很方便的查看某段代碼的AST語法樹結(jié)構(gòu)
3.代碼遷移
3.1 寫一個待轉(zhuǎn)換的Demo
<template>
<div>
A:{{num}}
</div>
</template>
<script>
import ehb from './EventHub';
export default {
name: 'B',
mounted() {
// 添加 eventHub 監(jiān)聽器
ehb.$on('inc', () => {
this.num += 1;
});
// 添加 eventHub 監(jiān)聽器
ehb.$once('inc', () => {
this.num * 100;
});
},
beforeUnmount() {
ehb.$off('inc');
},
};
</script>
3.2 需要做的事情
- 定位script標(biāo)簽內(nèi)的
$on$off$once$emit方法,提取他們的對象名 - 對象名,找到聲明它的代碼段
- 用 tiny_emitter 對象覆蓋掉之前 eventHub 提供的幾個廢棄方法
- 加 tiny_emitter 引用
- 文件輸出
轉(zhuǎn)換效果如下:
3.3 開工
安裝 GoGoCode
npm install gogocode
初始化 Vue 文件的 AST 對象
// 讀取文件內(nèi)容為ast對象
let ast = $(`待轉(zhuǎn)換vue文件的內(nèi)容`,{ parseOptions: { language: 'vue' } })
// 定位ast對象的script節(jié)點(diǎn)
let scriptAST = ast.find('<script></script>')
轉(zhuǎn)換邏輯:實現(xiàn)“3.2需要做的事情”
// 1. 遍歷script內(nèi)容$on、$off、$once和$emit
scriptAST.find([`$_$1.$on($_$2)`, `$_$1.$off($_$2)`, `$_$1.$once($_$2)`, `$_$1.$emit($_$2)`]).each(hubAST => {
// 1.1 使用hubAST.attr('callee.object.name')API,提取 ehb.$xxx(...) 的對象名
if (hubAST.attr('callee.object.name')) {
// 2. 找到eventHub聲明位置
let definitions = scriptAST.find(`import ${hubAST.attr('callee.object.name')} from '$_$'`)
const eventHub = `Object.assign(${ hubAST.attr('callee.object.name') } ,{
$on: (...args) => tiny_emitter.on(...args),
$once: (...args) => tiny_emitter.once(...args),
$off: (...args) => tiny_emitter.off(...args),
$emit: (...args) => tiny_emitter.emit(...args),
});
`
// 3. 遍歷聲明位置,用after API在聲明之后覆蓋之前的eventHub對象
definitions.each(def => {
if (!scriptAST.has(eventHub)) {
def.after(eventHub)
}
})
}
// 4. 添加tiny_emitter的引用
if (!scriptAST.has(`import tiny_emitter from 'tiny-emitter/instance'`)) {
scriptAST.prepend(`import tiny_emitter from 'tiny-emitter/instance';\n`)
}
})
最后輸出AST對象為字符串:
return ast.generate()
具體實現(xiàn)代碼: playground
4.最后總結(jié)下
這些代碼用到 GoGoCode 實現(xiàn)的AST操作:
-
$.find API用來定位
$on$off$once$emit,輸出AST對象 -
xxx.attr 用來提取AST對象的屬性,例如這段代碼里獲取
ehb.$on( ...... )對象名ehb - 使用 has API來判斷AST中是否已經(jīng)存在某個節(jié)點(diǎn)
- xxx.after 向相應(yīng)AST后添加一個AST對象
- xxx.prepend 向相應(yīng)AST前添加一個AST對象
都是很熟悉的操作有沒有!
這里分享了一些eventHub轉(zhuǎn)換實現(xiàn)的思路和GoGoCode的用法,希望能夠得到大家的意見建議,如果發(fā)現(xiàn)了代碼的問題,歡迎給我們提issue https://github.com/thx/gogocode/issues
感謝您的閱讀,祝你有美好的一天!