我的思路是使用 mixin 得知 onShow 被触发后去回调 setup 中 onShow 设置的函数
setup 中的代码会是这样的
setup(props, ctx) {
onLoad((...arg: any) => {
console.log("onLoad", arg);
});
},
在 app.vue 中 mixin
export default Vue.extend({
mpType: "app",
mixins: [vueLifeCycleMixin],
});
vueLifeCycleMixin 的具体实现
import { defineComponent, getCurrentInstance } from "@vue/composition-api";
import Vue from "vue";
export const vueLifeCycleMixin = Vue.mixin(
defineComponent({
onLoad: optionsWarp("onLoad"),
onShow: optionsWarp("onShow"),
}),
);
export const onShow = onFunWarp("onShow");
export const onLoad = onFunWarp("onLoad");
function optionsWarp(name: string) {
return function (this: any, ...args: any[]) {
const field = generateFieldName(name);
if (Array.isArray(this[field])) {
(this[field] as any).forEach((el: any) => el(...args));
}
};
}
function generateFieldName(name: string) {
return `__${name}`;
}
function onFunWarp(name: string) {
name = generateFieldName(name);
return (cb: Function) => {
var vm = getCurrentInstance() as any;
if (!vm) {
return console.warn("读取vm实例失败,请确保在 setup 中执行");
}
if (!vm[name]) {
vm[name] = [];
}
vm[name].push(cb);
};
}
2 个评论
要回复文章请先登录或注册
啃一口Apple
毛学生