在Uniapp的组件中监听页面的onShow和onHide事件

根据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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值