问题
多层级页面都使用同一个组件容器,naigateTo跳转页面时,组件没有销毁,导致多层级页面同时存在该组件容器,导致调用接口等操作重复执行。
// 页面A
<common></common>
// 页面B
<common></common>
// 页面C
<common></common>
A页面 -> B页面 -> C页面 ( -> 为跳转页面)
解决办法:
-
navigateTo改成redirectTo,页面跳转时,组件会销毁,但如需返回上一个页面,则该方案不可行。 -
使用
v-if,给容器组件使用v-if条件判断,区分不同的页面。比如:可使用路由层级。// store // 全局的页面层级变量,当前是第几级 export default new Vuex.Store({ state: { curPageRouteIndex: '' // 1:一级页面 2: 二级页面 ...... }, mutations: { setCurPageRouteIndex(state, data) { state.curPageRouteIndex = data } }, actions: { setCurPageRouteIndex({ commit }, data) { commit('setCurPageRouteIndex', data); } } })// A页面 <common v-if="curPageIndex === curPageRouteIndex"></common> <script> const len = getCurrentPages().length export default { data() { return { curPageIndex: "" // 当前页面层级 } }, computed() { curPageRouteIndex() { return this.$store.state.curPageRouteIndex }, }, // 注意获取这部分代码应写在onShow方法中,因为如果使用全局mixins的话,其他生命周期会被执行多次,onShow只会执行一次 onShow() { this.curPageIndex = getCurrentPages().length // 1 this.$store.dispatch('setCurPageRouteIndex', this.curPageIndex) } } </script>B页面、C页面的内容与A页面内容一样。