动态keep-alive

自己做了一个,从home到about时,about要做缓存,从manage进入about时about又不做缓存;

实现原理

路由跳转之前判断是否需要缓存,需要的话讲需要缓存的组件的 name 值存入一个数组,保存到vuex。app.vue 里面导入需要缓存的组件名

我是用脚手架搭建的

需要用到的东西有vue-router和vuex,实现方式如下

app.vue








store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    needInclude:[]
  },
  mutations: {
    saveNeedInclude(state,param){
      state.needInclude = param
    }
  },
  actions: {

  }
})

router.js

import Vue from 'vue'
import Router from 'vue-router'
import store from './store'

import Home from './views/index'
import About from './views/about'
import Manage from './views/manage/index'

Vue.use(Router)

let router = new Router({
  routes: [
    {
      redirect: 'home',
      path: '/'
    },
    {
      name: 'home',
      path: '/home',
      component: Home
    },
    {
      name: 'about',
      path: '/about',
      component: About,
      beforeEnter:(to,from,next)=>{
        if(from.name == 'home'){
          store.commit('saveNeedInclude',['about'])
        }else{
          store.commit('saveNeedInclude',[])
        }
        next()
      }
    },
    {
      name: 'manage',
      path: '/manage',
      component: Manage
    }
  ]
})


export default router

你可能感兴趣的:(动态keep-alive)