当组件在keep-alive中被切换时,缓存一次后mounted就不执行了,而activated和deactivated这两个钩子函数会被执行。
activated:被 keep-alive 缓存的组件激活时调用。
deactivated:被 keep-alive 缓存的组件停用时调用。
keep-alive还可以接受两个参数,include和exclude,允许组件有条件地缓存。
二者都可以用字符串或正则表达式。
include:只有匹配的组件会被缓存。
exclude:任何被匹配的组件将不会被缓存
先做一个简单的tab:
结果:
代码:
<template>
<div>
<p>keep-alive用法</p>
<div class="tabs">
<div
v-for="(item,index) in tabs"
:key="index"
:class="['tab',index==idx?'active':'']"
@click="toTab(item.path,index)"
>{{item.name}}</div>
</div>
<!-- 需要缓存的组件 -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: "tab1", path: "/HelloWorld" },
{ name: "tab2", path: "/tabContent" }
],
idx: 0
};
},
methods: {
toTab(url, index) {
this.idx = index;
this.$router.push({
path: url
});
}
}
};
</script>
路由:
主要要设置 meta:{ keepAlive:true }
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home,
children:[
{
path: '/',
name:'HelloWorld',
component: () => import( './components/HelloWorld.vue'),
meta:{
keepAlive:true
}
},
{
path: '/HelloWorld',
name:'HelloWorld',
component: () => import( './components/HelloWorld.vue'),
meta:{
keepAlive:true
}
},
{
path: '/tabContent',
name:'tabContent',
component: () => import( './components/tabContent.vue'),
meta:{
keepAlive:true
}
},
]
},
]
})
include用法:
注意:匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。
<template>
<div>
<p>keep-alive中include用法</p>
<div class="tabs">
<div
v-for="(item,index) in tabs"
:key="index"
:class="['tab',index==idx?'active':'']"
@click="toTab(index)"
>{{item.name}}</div>
</div>
<!-- include用法 -->
<!-- 这里只有HelloWorld会被缓存 -->
<keep-alive include="HelloWorld">
<HelloWorld v-if="idx==0"/>
<tabContent v-if="idx==1"/>
</keep-alive>
</div>
</template>
<script>
import HelloWorld from '../components/HelloWorld'
import tabContent from '../components/tabContent'
export default {
data() {
return {
tabs: [
{ name: "tab1"},
{ name: "tab2"}
],
idx: 0
};
},
components:{HelloWorld, tabContent},
methods: {
toTab(index) {
this.idx = index;
}
}
};
</script>