首页 > 其他 > 详细

vue keep-alive

时间:2021-04-24 20:22:43      阅读:21      评论:0      收藏:0      [点我收藏+]

 keep-alive 会把其包裹的所有组件都缓存起来

<div id="app">
    <keep-alive :include="include">
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" />
</div>

include 参数 类型 Array

  字符串或正则表达式, 只有名称匹配的组件会被缓存

app.vue***

export default {
  name: "app",
  data: () => ({
    include: []
  }),
  watch: {
    $route(to, from) {
      //如果 要 to(进入) 的页面是需要 keepAlive 缓存的,把 name push 进 include数组
      if (to.meta.keepAlive) {
        !this.include.includes(to.name) && this.include.push(to.name);
      }
      //如果 要 form(离开) 的页面是 keepAlive缓存的,
      //再根据 deepth 来判断是前进还是后退
      //如果是后退
      if (from.meta.keepAlive && to.meta.deepth < from.meta.deepth) {
        var index = this.include.indexOf(from.name);
        index !== -1 && this.include.splice(index, 1);
      }
    }
  }
}
import Vue from ‘vue‘
import VueRouter from ‘vue-router‘
Vue.use(VueRouter)
const constantRoutes = [
  {
    path: ‘/‘,
    name: "home",
    component: () => import("@/page/home/index"),
    meta: {
      title: "首页",
      deepth: 0.5
    }
  },
  {
    path: ‘/list‘,
    name: "list",
    component: () => import("@/page/msg/list"),
    meta: {
      title: "消息列表",
      deepth: 1,
      keepAlive: true //需要被缓存
    }
  },
  {
    path: ‘/msg‘,
    name: "msg",
    component: () => import("@/page/msg/index"),
    meta: {
      title: "消息",
      deepth:
    }
  },
]

const router = new VueRouter({
  routes: constantRoutes
})

export default router

备注: 我们包裹的组件都有字的名字(name)

vue keep-alive

原文:https://www.cnblogs.com/shenjilin/p/14697496.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!