可以通过在路由配置文件中设置路由元信息来实现这个需求。

在路由配置文件中设置directory页面的路由元信息,告诉Vue不要使用keepalive:

{
  path: '/directory',
  name: 'directory',
  component: Directory,
  meta: {
    keepAlive: false // 不使用keepalive
  }
}

在路由配置文件中设置详情页的路由元信息,告诉Vue使用keepalive:

{
  path: '/detail',
  name: 'detail',
  component: Detail,
  meta: {
    keepAlive: true // 使用keepalive
  }
}

在Directory组件的路由跳转方法中,跳转到详情页时传递一个参数,告诉详情页是否需要使用keepalive:

// 在Directory组件中跳转到详情页时传递参数
this.$router.push({
  path: '/detail',
  query: {
    keepAlive: true // 需要使用keepalive
  }
})

在Detail组件中的mounted生命周期钩子中,根据传递的参数来判断是否需要使用keepalive:

// 在Detail组件中根据参数判断是否需要使用keepalive
if (this.$route.query.keepAlive) {
  this.$store.commit('setKeepAlive', this.$route.name)
}

在store中设置一个状态来保存需要使用keepalive的路由名:

// 在store中设置需要使用keepalive的路由名
const state = {
  keepAliveRoutes: []
}

const mutations = {
  setKeepAlive(state, name) {
    if (!state.keepAliveRoutes.includes(name)) {
      state.keepAliveRoutes.push(name)
    }
  },
  removeKeepAlive(state, name) {
    const index = state.keepAliveRoutes.indexOf(name)
    if (index !== -1) {
      state.keepAliveRoutes.splice(index, 1)
    }
  }
}

在App.vue组件中监听路由变化,在需要使用keepalive的路由组件中添加keep-alive组件:

<template>
  <div id='app'>
    <router-view v-if='$route.meta.keepAlive || keepAliveRoutes.includes($route.name)'/>
  </div>
</template>

<script>
export default {
  computed: {
    keepAliveRoutes() {
      return this.$store.state.keepAliveRoutes
    }
  },
  watch: {
    $route(to, from) {
      if (to.meta.keepAlive) {
        this.$store.commit('setKeepAlive', to.name)
      } else {
        this.$store.commit('removeKeepAlive', to.name)
      }
    }
  }
}
</script>

这样就可以实现从主页进入directory页面不用keepalive,从directory页面进入详情页并从详情页返回使用keepalive的需求了。

Vue3路由配置:主页不缓存,Directory页面不缓存,Detail页面缓存实现方法

原文地址: https://www.cveoy.top/t/topic/nfFZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录