vue3 使用router4 keepalive问题

项目从vue2升级到vue3,路由也紧跟着升级到了4,然后在使用keep-alive的时候一直不生效,就去查文档
vue2.x与vue3.0的App.vue配置有差异,在App.vue配置信息如下:
vue2.x中,router-view可整个放入keepalive中,如下:

<template>
	<!-- vue2.x配置 -->
   <keep-alive>
    <router-view v-if="$route.meta.keepAlive" />
  </keep-alive>
  <router-view v-if="!$route.meta.keepAlive"/>
</template>
<template>
  <!-- vue3.0配置 -->
  <router-view v-slot="{ Component }">
    <keep-alive>
      <component :is="Component"  v-if="$route.meta.keepAlive"/>
    </keep-alive>
    <component :is="Component"  v-if="!$route.meta.keepAlive"/>
  </router-view> 
</template>

但是假如按照这样配置,会有一个问题,假如A页面时缓存页面,跳转到B页面也是缓存页面的话 就会是报Uncaught (in promise) TypeError: parentComponent.ctx.deactivate is not a function 这个错误
所以 需要再中间中配置key值,来表示组件的唯一性和对应关系,如::key="$route.path"
而且 不要动态修改to.meta.keepAlive的值控制是否缓存。

会存在第一次将to.meta.keepAlive设置为true是还是会发送请求,因为第一次是创建组件,没有缓存,需要缓存后,下一次进入才不会发送请求。因为如果最开始进入的时候to.meta.keepAlive值为false的话,渲染的是没有使用keep-alive的组件。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3.x中,可以使用keep-alive组件来实现组件的缓存。下面是使用keep-alive的方法: 1. 在App.vue文件中,使用router-view来渲染组件,并使用v-slot指令来获取组件对象。 ```html <template> <router-view v-slot="{ Component }"> <keep-alive> <component :is="Component" v-if="$route.meta.keepAlive" /> </keep-alive> <component :is="Component" v-if="!$route.meta.keepAlive" /> </router-view> </template> ``` 2. 在需要缓存的组件中,使用keep-alive组件来包裹。 ```html <template> <keep-alive> <!-- 需要缓存的组件内容 --> </keep-alive> </template> ``` 3. 在辅助文件(例如keepAliveStore.ts)中,可以使用pinia来定义一个store来管理缓存队列。可以使用setKeepAlive方法将组件添加到缓存队列中,使用removeKeepAlive方法将组件从缓存队列中移除。 ```javascript import { defineStore } from 'pinia' export interface KeepAliveState { keepAliveComponents: Array<any> } export const keepAliveStore = defineStore('keepAlive', { state: (): KeepAliveState => { return { keepAliveComponents: [] } }, getters: { getKeepAliveComponents(state) { return state.keepAliveComponents } }, actions: { // 加入到缓存队列 setKeepAlive(component: any) { if (!this.keepAliveComponents.includes(component)) { this.keepAliveComponents.push(component) } }, // 从缓存队列移除 removeKeepAlive(component: any) { const index = this.keepAliveComponents.indexOf(component) if (index !== -1) { this.keepAliveComponents.splice(index, 1) } } } }) ``` 通过以上方法,你可以在Vue 3.x中使用keep-alive来实现组件的缓存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值