美文网首页
vue动态使用keepalive缓存页面

vue动态使用keepalive缓存页面

作者: 码农私房菜 | 来源:发表于2024-03-13 10:50 被阅读0次

    vuex

    // src/store/modules/tagsView.js
    const state = {
      // 用户访问过的页面 就是标签栏导航显示的一个个 tag 数组集合
      visitedViews: [],
      // 实际 keep-alive 的路由。可以在配置路由的时候通过 meta.noCache 来设置是否需要缓存这个路由 默认都缓存。
      cachedViews: ['Home', 'Order'],
      noCachedViews: []
    }
    const mutations = {
      ADD_NO_CACHED_VIEWS: (state, view) => {
        state.noCachedViews = view
      },
    }
    export default {
      namespaced: true,
      state,
      mutations,
      // actions
    }
    

    主路由

    // src/layout/components/AppMain.vue
    <template>
      <section class="app-main">
        <transition name="fade-transform" mode="out-in">
          <keep-alive :include="cachedViews" :exclude="noCachedViews">
            <router-view :key="key" v-if="$route.meta.keepAlive" />
          </keep-alive>
        </transition>
        <transition name="fade-transform" mode="out-in">
          <router-view :key="key" v-if="!$route.meta.keepAlive" />
        </transition>
      </section>
    </template>
    
    <script>
    export default {
      name: 'AppMain',
      computed: {
        cachedViews() {
          return this.$store.state.tagsView.cachedViews
        },
        noCachedViews() {
          return this.$store.state.tagsView.noCachedViews
        },
        key() {
          return this.$route.path
        },
      }
    }
    </script>
    

    入口main文件

    // src/main.js
    import store from './store'
    router.afterEach(() => {
      // 重置不缓存的页面名称
      setTimeout(() => {
        store.commit('tagsView/ADD_NO_CACHED_VIEWS', [])
      }, 2000)
    })
    

    页面交互逻辑

    // src/views/home/index.vue
     methods: {
        // 不缓存页面数据
        closeSelectedTag(view) {
          if (view.name) {
            this.$store.commit('tagsView/ADD_NO_CACHED_VIEWS', [view.name])
          }
        },
    }
    

    相关文章

      网友评论

          本文标题:vue动态使用keepalive缓存页面

          本文链接:https://www.haomeiwen.com/subject/lnnbzdtx.html