uni-app H5 PC适配 Mixins 生命周期函数不调用
uni-app H5 PC适配 Mixins 生命周期函数不调用
操作步骤:
pages.json 加入
"leftWindow": {
"path": "responsive/left-window.vue",
"style": {
"width": "350px"
}
},
"topWindow": {
"path": "responsive/top-window.vue",
"style": {
"height": "60px"
}
},
代码为 TS开发,使用了 vue-property-decorator
预期结果:
页面基类 onLoad, onShow 等生命周期函数正常调用
实际结果:
只有页面自身生命周期函数被调用,Mixins 中的未调用
bug描述:
加入宽屏适配(https://uniapp.dcloud.net.cn/adapt)后,页面 Mixins 时,基类生命周期函数不调用
更多关于uni-app H5 PC适配 Mixins 生命周期函数不调用的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在 uni-app 的宽屏适配方案中,leftWindow 和 topWindow 作为独立窗口,其生命周期与主页面是分离的。当你在这些窗口组件中使用 Mixins 时,需要确保 Mixins 中的生命周期函数能被正确调用。
问题原因:
- leftWindow/topWindow 是独立的 Vue 组件,不是页面组件
- 这些窗口组件的生命周期与主页面不同步
- Mixins 中的页面级生命周期(onLoad、onShow)在窗口组件中不会自动触发
解决方案:
- 明确窗口组件类型 leftWindow/topWindow 是组件而非页面,应使用 Vue 组件的生命周期:
import { Component, Vue } from 'vue-property-decorator'
@Component
export default class LeftWindow extends Vue {
mounted() {
// 替代 onLoad
this.initData()
}
activated() {
// 替代 onShow
this.onWindowShow()
}
private initData() {
// 初始化逻辑
}
private onWindowShow() {
// 显示时逻辑
}
}
- 调整 Mixins 设计 为窗口组件创建专用的 Mixins:
// window-mixin.ts
import { Component, Vue } from 'vue-property-decorator'
@Component
export class WindowMixin extends Vue {
mounted() {
if (this['onWindowLoad']) {
this['onWindowLoad']()
}
}
activated() {
if (this['onWindowShow']) {
this['onWindowShow']()
}
}
}
- 在窗口组件中使用
import { Component, Mixins } from 'vue-property-decorator'
import { WindowMixin } from './window-mixin'
@Component
export default class LeftWindow extends Mixins(WindowMixin) {
onWindowLoad() {
// 窗口加载逻辑
}
onWindowShow() {
// 窗口显示逻辑
}
}
- 检查编译配置 确保 tsconfig.json 中的装饰器配置正确:
{
"compilerOptions": {
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true
}
}


