根据Uniapp的官方文档,onShow和onHide事件只能在页面中使用。
因此,无法在组件中监听页面的onShow和onHide事件。
通过查看Uniapp的源代码,发现在组件中可以通过程序化的事件侦听器的方式监听到页面的onShow和onHide事件,代码如下:
// components/page-container.vue
{
created() {
const handleShow = () => {
// TODO...
};
const handleHide = () => {
// TODO...
};
this.$root.$on('hook:onShow', handleShow);
this.$root.$on('hook:onHide', handleHide);
this.$once('hook:beforeDestroy', () => {
this.$root.$off('hook:onShow', handleShow);
this.$root.$off('hook:onHide', handleHide);
});
handleShow();
},
}
2024年5月7日更新:以上代码只在uniapp的app开发并且使用的是Vue2才生效
在小程序平台下,可以使用以下Vue3代码
// src/hooks/usePageVisibility.ts
// @ts-ignore
import { injectHook, getCurrentInstance, isInSSRComponentSetup, ref } from 'vue';
const createHook =
(lifecycle: string) =>
(hook: () => void, target = getCurrentInstance()) => {
!isInSSRComponentSetup && injectHook(lifecycle, hook, target);
};
const onPageShow = createHook('onPageShow');
const onPageHide = createHook('onPageHide');
export default function usePageVisibility() {
const visibility = ref(false);
onPageShow(() => {
visibility.value = true;
});
onPageHide(() => {
visibility.value = false;
});
return visibility;
}
使用方法如下
<!-- src/pages/home.vue -->
<script setup lang="ts">
import usePageVisibility from '../hooks/usePageVisibility';
const pageVisibility = usePageVisibility();
</script>
<template>
<view v-if="pageVisibility">可见性</view>
</template>
文章转载于:https://zhuanlan.zhihu.com/p/681113308
689

被折叠的 条评论
为什么被折叠?



