vue中keepAlive缓存及缓存下的钩子函数

在开发中,经常有从列表跳转到详情页,再返回的时候之前的状态就没有了,所以需要缓存列表页的状态,这时候就需要保存状态,vue中提供了keep-alive组件来缓存状态

利用meta标签

1. 首先在路由中的meta标签中记录meta的属性为true

{
    path: "/userInfo",
    component: () => import("@/views/UserInfo/Index"),
    meta: {
      title: "首页",
      keepAlive: true // 缓存该页面
    }
  },

2.在创建router实例的时候加上scrollBehavior方法

const router = new VueRouter({
  routes,
  // 点击浏览器的前进后退或切换导航触发
  scrollBehavior: function (to, from, savedPosition) {
    return savedPosition || { x: 0, y: 0 }
  }
});

3.在需要缓存的router-view组件上包裹keep-alive组件

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

 

缓存下的钩子函数

当我们使用keepAlive缓存时,页面中的created,mounted将不起作用,要想在进入页面获取新的数据列表时。需要引用activateddeactivated

activated:keepAlive组件被激活时使用(一般在keep-alive组件下,返回页面需重新渲染列表,就在此钩子下调用)

deactivated:keepAlive组件被停用时调用

 

posted @ 2021-08-25 18:06  小黄花呐  阅读(1245)  评论(0编辑  收藏  举报