vue3在單個組件中實現(xiàn)類似mixin的事件調(diào)用
更新時間:2024年01月19日 15:11:40 作者:恍恍惚惚斯基
這篇文章主要為大家詳細介紹了vue3如何在單個組件中實現(xiàn)類似mixin的事件調(diào)用,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
簡單的訂閱發(fā)布功能
class MyDispatch { constructor() { this._dispatch_list = [] } register_on(id, command_type, func) { // 注冊事件 const dispatch_obj = { id, command_type, func: func } this._dispatch_list.push(dispatch_obj) } register_off(id) { // 移除事件 this._dispatch_list = this._dispatch_list.filter(item => item.id !== id) } dispatch(command_type, data) { // 觸發(fā)并執(zhí)行事件,根據(jù)command_type區(qū)分類型 for (let i = 0; i < this._dispatch_list.length; i++) { const dispatch_obj = this._dispatch_list[i] if (command_type === dispatch_obj.command_type) { dispatch_obj.func(data) } } } } // 混入的代碼 function testA(emits) { const data = '執(zhí)行成功咯!' emits.dispatch('do', data) } // 組件代碼 function mainTest() { const emits = new MyDispatch() emits.register_on('testB', 'do', testB) testA(emits) function testB(data) { console.log('testB 執(zhí)行,', data) } } mainTest()
運行結果
this綁定
function testA() { const data = '執(zhí)行成功咯!' const testB = this.testB if (testB) { testB(data) } } function mainTest() { const thisArg = { testB: testB } testA.call(thisArg) function testB(data) { console.log('testB 執(zhí)行,', data) } } mainTest()
執(zhí)行結果同上
到此這篇關于vue3在單個組件中實現(xiàn)類似mixin的事件調(diào)用的文章就介紹到這了,更多相關vue3 mixin內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VUE實現(xiàn)一個Flappy Bird游戲的示例代碼
這篇文章主要介紹了VUE實現(xiàn)一個Flappy Bird的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04vite+vue3中require?is?not?defined問題及解決
這篇文章主要介紹了vite+vue3中require?is?not?defined問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05vue 基于abstract 路由模式 實現(xiàn)頁面內(nèi)嵌的示例代碼
這篇文章主要介紹了vue 基于abstract 路由模式 實現(xiàn)頁面內(nèi)嵌的示例代碼,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12Vue中@keyup.enter?@v-model.trim的用法小結
這篇文章主要介紹了Vue中@keyup.enter?@v-model.trim的用法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-12-12