MST

星途 面试题库

面试题:Vue Keep - Alive结合路由实现页面缓存,如何动态控制缓存的组件?

假设你正在开发一个单页应用,使用Vue Keep - Alive结合路由实现页面缓存。现在有需求,根据用户的权限动态决定某些组件是否需要被缓存。请描述实现该功能的思路,并给出关键代码示例。
21.2万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 在路由配置中,为需要根据权限判断缓存的路由添加自定义元信息,例如 meta: { cache: true, requirePermission: '特定权限标识' }
  2. beforeEach 路由守卫中,获取当前用户权限信息。
  3. 根据用户权限和路由元信息判断该组件是否应该被缓存。
  4. 在使用 keep - alive 时,通过动态绑定 includeexclude 属性来控制组件的缓存。

关键代码示例

  1. 路由配置
const routes = [
  {
    path: '/example',
    name: 'Example',
    component: () => import('@/views/Example.vue'),
    meta: {
      cache: true,
      requirePermission: 'admin' // 假设只有admin权限可缓存
    }
  }
]
  1. 路由守卫
import router from './router'
import store from './store' // 假设权限信息存储在vuex中

router.beforeEach((to, from, next) => {
  const userPermission = store.getters.userPermission // 获取用户权限
  if (to.meta.cache && to.meta.requirePermission) {
    if (userPermission.includes(to.meta.requirePermission)) {
      // 用户有权限,添加到缓存列表
      if (!store.state.cacheComponents.includes(to.name)) {
        store.commit('addCacheComponent', to.name)
      }
    } else {
      // 用户无权限,从缓存列表移除
      if (store.state.cacheComponents.includes(to.name)) {
        store.commit('removeCacheComponent', to.name)
      }
    }
  }
  next()
})
  1. Vuex配置
const state = {
  cacheComponents: []
}

const mutations = {
  addCacheComponent(state, componentName) {
    state.cacheComponents.push(componentName)
  },
  removeCacheComponent(state, componentName) {
    state.cacheComponents = state.cacheComponents.filter(name => name!== componentName)
  }
}

const getters = {
  cacheComponents: state => state.cacheComponents
}

export default {
  state,
  mutations,
  getters
}
  1. 使用 keep - alive
<template>
  <keep - alive :include="cacheComponents">
    <router - view />
  </keep - alive>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  computed: {
  ...mapGetters(['cacheComponents'])
  }
}
</script>