uniapp vue3 $on/$once/$off 的替代方案
僅作參考 僅作參考 僅作參考 並且只支援頁面生命周期使用 不支援組件 不支援頁面函數方法 下面說了思路需要的話自己添加
今天用到 $once 時發現報錯了,原理是vue3移除了該api。我一開始想的是 自己註冊全局方法 如下
app.config.globalProperties.$once = function(cycle, callback) {
let flag = true;
app.mixin({
[cycle]() {
if (flag) {
flag - false
callback()
}
}
})
}
但是發現我這樣是全局注入,我想要的是局部單頁面,並且我沒辦法刪除註冊後的方法,通過flag的話也不規範。
然後我就在頁面中輸出this,發現對象上沒有周期函數,***,最後竟在this._上獲取到了,不過我又發現為什麼是數組,恰飯的時候想起來mixins混入,可能是讓開發者清楚自己混入了多少文件吧,ok 經歷說過了 下面放程式碼:
### main.js
import $mixins from './common/mixins.js'
***
app.mixin($mixins)
### mixins.js
export default{
methods: {
$once(cycle,callback){
if(this._[cycle]===undefined){
this._[cycle][0]=[]
}
this._[cycle][0] = function(){
callback()
return this._[cycle][0]===undefined?function(){}:this._[cycle][0]
}.bind(this)()
},
$on(cycle,callback,fnIndex){
this._[cycle].push(function(){
callback.__proto__.fnIndex=fnIndex
callback()
}.bind(this))
},
$off(fnIndex){
let num=0;
for (let item of this._[cycle]) {
if(item.__proto__.fnIndex===fnIndex){
item.splice(num,1)
return
}
num++
}
}
}
}