keep-alive 缓存了多个页面后,onMouted执行多次
Vue version
3.2.45
Link to minimal reproduction
https://codesandbox.io/s/musing-tristan-jjobbr?file=/src/views/components/Page2.vue
Steps to reproduce
首次执行1次onMounted 打印,page1 但点击切换到page2, 再点击page1 会发现执行了多次onMounted
What is expected?
希望只执行当前页面的onMounted,只打印一次
What is actually happening?
执行多次onMouted
System Info
No response
Any additional comments?
No response
Thanks for the report, can you provide a minimal reproduction without dependencies on vue-router and vant?
@daisybaicai
改写一下index.vue :3-16 代码 就不会打印l两次
<router-view v-slot="{ Component }">
<keep-alive v-if="$route.meta.keepAlive">
<component :is="Component" :key="$route.name" />
</keep-alive>
<component :is="Component" v-else :key="$route.name" />
</router-view>
In your App.vue, it will preserve one Home component instances.
So it will mounted twice when you navigate to page1, because the preserved instances will mount Page1 component one time, and the <component :is="Component" v-if="!$route.meta.keepAlive" :key="$route.fullPath" />
will mount another time.
@daisybaicai
改写一下index.vue :3-16 代码 就不会打印l两次
<router-view v-slot="{ Component }"> <keep-alive v-if="$route.meta.keepAlive"> <component :is="Component" :key="$route.name" /> </keep-alive> <component :is="Component" v-else :key="$route.name" /> </router-view>
这样写直接就缓存就失效了
@daisybaicai 改写一下index.vue :3-16 代码 就不会打印l两次
<router-view v-slot="{ Component }"> <keep-alive v-if="$route.meta.keepAlive"> <component :is="Component" :key="$route.name" /> </keep-alive> <component :is="Component" v-else :key="$route.name" /> </router-view>
这样写直接就缓存就失效了
那要改的话怎么改?
@daisybaicai 改写一下index.vue :3-16 代码就不会打印l两次
<router-view v-slot="{ Component }"> <keep-alive v-if="$route.meta.keepAlive"> <component :is="Component" :key="$route.name" /> </keep-alive> <component :is="Component" v-else :key="$route.name" /> </router-view>
这样写直接保存就失效了
那要改的话怎么改?
在App.vue中改为
<RouterView />
就好了