业务场景:详情页面A进入编辑页面B,编辑页面B进入选择页面C,选择页面C返回编辑页面B
假如是vue2的话 可以通过判断路由,来使变量初始化即可,因为vue2变量都是在data里面定义的,所以可以通过可以Object.assign(vm.$data, vm.$options.data())
直接初始化变量。但是因为是vue3重构 我们的变量都是在setup中,就不能通过这种办法来初始化变量
方法1 错误
通过meta里面的keepAlive来控制,我在a进入b的时候
onBeforeRouteLeave((to, from, next) => {
console.log('看看路由离开', to, from)
if (to.name === 'creatShoes') {
to.meta.keepAlive = false
}
next()
})
让这个页面不缓存,然后在b进入c的时候再让页面缓存
onBeforeRouteLeave((to, from, next) => {
console.log('看看路由离开', to, from)
if (to.name === 'selectLocation') {
to.meta.keepAlive = true
}
next()
})
经过这样一番操作,虽然a进入b的时候,b不缓存了,但是b去c 再回来的时候还是不缓存,明明已经设置了true了 为什么还是不缓存
分析一下代码
<template>
<div id="app">
<!-- vue3.0配置 -->
<router-view v-slot="{ Component }">
<keep-alive>
<component
:is="Component"
v-if="$route.meta.keepAlive"
:key="$route.path"
/>
</keep-alive>
<component
:is="Component"
v-if="!$route.meta.keepAlive"
/>
</router-view>
</div>
</template>
我们看,我们设置了false的时候,他进入的是下面的代码块,所以不管我们设置成什么,他都在下面的代码块,没有keep-alive包裹,所以也就不是缓存页面
方法2 通过onUnmounted 还是错误
还是先设置b页面时缓存页面
onBeforeRouteLeave((to, from, next) => {
console.log('看看去了哪', to, from, shoesData)
// 假如去选择位置页面当前页面缓存
if (to.name !== 'selectLocation' || to.name !== 'washShoes') {
onUnmounted()
}
next()
})
假如b去的路由不是这两个的话 就让他销毁实例,也就清空了缓存数据
但是!!生命周期钩子函数只能用在setup中 不能用在路由钩子中
方法3 include 使用以下方法依然错误
<template>
<div id="app">
<!-- vue3.0配置 -->
<router-view v-slot="{ Component }">
<keep-alive :include="cachePage">
<component :is="Component" />
</keep-alive>
</router-view>
</div>
</template>
setup() {
const cachePage = ref(['shoeDetail', 'creatShoes', 'washShoes'])
onBeforeRouteLeave((to, from, next) => {
if (from.name === 'selectLocation' && to.name === 'creatShoes') {
// 假如是从创建到选择位置的话 就是缓存页面
cachePage.value = ['shoeDetail', 'creatShoes', 'washShoes']
} else if (from.name === 'washShoes' && to.name === 'creatShoes') {
cachePage.value = ['shoeDetail', 'creatShoes', 'washShoes']
} else {
cachePage.value = ['shoeDetail', 'washShoes']
}
next()
})
return {
cachePage
}
}
因为app.vue文件只会运行一次,所以需要用到store
onBeforeRouteLeave((to, from, next) => {
let cachePage = store.state.cachePage
if (to.name === 'selectLocation' && from.name === 'creatShoes') {
// 假如是从创建到选择位置的话 就是缓存页面
cachePage = ['shoeDetail', 'creatShoes', 'washShoes']
} else if (to.name === 'washShoes' && from.name === 'creatShoes') {
cachePage = ['shoeDetail', 'creatShoes', 'washShoes']
} else {
cachePage = ['shoeDetail', 'washShoes']
}
store.commit('updatedCache', cachePage)
next()
})
注意事项,用include这个数组的时候,一定要在页面上定义name,光在路由文件里面定义是没有用的