每次进入页面都触发的功能(v3)
# 功能
vue3项目中,onMounted函数在组件加载完成后执行,点击进入其他页面再返回,onMounted中的内容不执行,导致数据未更新
此方法可以实现在每次进入页面时,都执行某些操作(类uni-app的onShow函数)
# 实现
usePageActive.js文件
const usePageActive = () => {
const route = useRoute();
const currentRouteName = computed(() => route.name && route.name.toString());
const onPageActive = (callback, routes) => {
const routeName = route.name && route.name.toString();
if (hc.userAgent.isJKY) {
hc.onPageActive(callback); // 内嵌在app中时,可以调用原生的方法
return;
}
function activeFunc() {
if (routes && routes.indexOf(currentRouteName.value) > -1) {
callback();
} else if (currentRouteName.value === routeName) {
callback();
}
}
onMounted(() => {
if (window.history && window.history.pushState) {
window.addEventListener('popstate', activeFunc, false);
}
});
onUnmounted(() => {
window.removeEventListener('popstate', activeFunc);
});
};
return { onPageActive };
};
export default usePageActive;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
单个页面中:
<script setup>
import usePageActive from './usePageActive';
const { onPageActive } = usePageActive();
onPageActive(() => {
getList(); // 具体的操作
});
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
上次更新: 2024/03/12, 18:10:43