vue keepalive的使用
vue里提供了keep-alive组件用来缓存状态(keep-alive本身是vue2.0的功能,并不是vue-router的,所以在vue1.0版本是不支持的)。
基本使用
<keep-alive>
<router-view></router-view>
</keep-alive>
但是并不是每个页面都是要缓存的所以有了动态使用:
1.在meta添加keepAlive:ture
<keep-alive>
<router-view v-if="$route.meta.keepAlive"> </router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"> </router-view>
路由中
{name:'details',path:'/details',meta:{keepAlive:ture}}
但是再次点进详情页数据会不刷新,所以要用到activated和deactivated
activated() {
// 重新获取数据
},
deactivated() {
//销毁
}
2.使用include、exclude属性(include是需要缓存的组件;exclude是除了某些组件都缓存;)
例:(exclude一样)
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<router-view ></router-view>
</keep-alive>
<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
<router-view ></router-view>
</keep-alive>
<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
<router-view ></router-view>
</keep-alive>
可以监听$router来控制include、exclude的值.