vue实现页面缓存功能

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vue实现页面缓存功能脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例为大家分享了vue实现页面缓存功能的具体代码,供大家参考,具体内容如下

主要利用keep-alive实现从列表页跳转到详情页,然后点击返回时,页面缓存不用重新请求资

一、在router里配置路由

在meta里定义页面是否需要缓存

import Vue From "vue";
import Router from "vue-router";

// 避免到当前位置的冗余导航
const originalPush = Router.PRototyPE.push
Router.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router);
export default new Router({
  base: '',
  routes: [{
      path: "/",
      name: "index",
      component: () => import("@/layout"),
      redirect: '/LOGin',
      children: [
        {
          path: 'dutySheet',
          name: 'dutySheet',
          component: () => import("@/pages/dashboard/DutySheet")
        },
        {
          path: 'seArchWord',
          name: 'searchWord',
          component: () => import("@/pages/dailyReportManage/searchWord/index"),
          meta: {
            keepAlive: true // 需要缓存页面
          }
        },
        // 匹配维护
        {
          path: "troopAction",
          name: "troopAction",
          component: () => import("@/pages/Dashboard/TroopAction"),
          meta: {
            keepAlive: false//  不需要缓存
          }
     },
      ]
    },
  ]
});

二、配置APP.vue

使用keep-alive来进行缓存

<keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>

三、点击返回按钮时调用this.$router.back()方法就可以了

// 返回
      bacKBnt(){
        this.$router.back()
      },

四、清除缓存

只针对跳转到"exhibITionWord"或"exhibitionWeekWord"页面才进行缓存,跳转其他页面不用缓存。

beforeRouteLeave(to, from, next) {
      if (to.name == 'exhibitionWord' || to.name == 'exhibitionWeekWord') { // 需要缓存的路由name
          from.meta.keepAlive = true
          next()
        }else{
          from.meta.keepAlive = false
          next()
      }
    },

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的vue实现页面缓存功能全部内容,希望文章能够帮你解决vue实现页面缓存功能所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:vue