解决uniapp切换菜单栏时会触发onshow的问题
时间: 2023-08-04 12:05:28 浏览: 74
如果你不想在 uni-app 切换菜单栏时触发 onShow 函数,可以在 App.vue 中实现一个全局的状态管理,用一个变量来记录当前页面是否需要触发 onShow 函数。具体实现方式如下:
1. 在 App.vue 中定义一个全局变量 `needShow`,用来标识当前页面是否需要触发 onShow 函数。
```html
<template>
<div>
<!-- 页面内容 -->
<router-view :needShow="needShow"></router-view>
</div>
</template>
<script>
export default {
data() {
return {
needShow: true
};
},
methods: {
// 切换菜单栏时,设置 needShow 为 false,不触发 onShow 函数
switchTab(e) {
const index = e.index;
if (index === 0) {
this.needShow = false;
} else {
this.needShow = true;
}
}
}
};
</script>
```
2. 在页面组件中,利用 props 接收 App.vue 中传递的 `needShow` 变量,并在 onShow 函数中根据 `needShow` 变量的值来判断是否需要执行相关操作。
```html
<template>
<div>
<!-- 页面内容 -->
</div>
</template>
<script>
export default {
props: {
needShow: {
type: Boolean,
default: true
}
},
onShow() {
if (this.needShow) {
// 执行需要的操作
// TODO
}
// 重置 needShow 为 true,确保下次切换菜单栏时能够触发 onShow 函数
this.$emit("update:needShow", true);
}
};
</script>
```
在这个例子中,我们在 App.vue 中定义了一个全局变量 `needShow`,并在切换菜单栏时根据当前选中的菜单项来设置 `needShow` 的值。在页面组件中,我们利用 props 接收 App.vue 中传递的 `needShow` 变量,并在 onShow 函数中根据 `needShow` 变量的值来判断是否需要执行相关操作。需要注意的是,我们在页面组件中通过 `$emit` 方法来更新 `needShow` 变量的值,确保下次切换菜单栏时能够触发 onShow 函数。