keep-alive
可以在組件切換時,保存其包裹的組件的狀態,使其不被銷毀,防止多次渲染。其擁有兩個獨立的生命周期鈎子函數 actived 和 deactived,使用keep-alive
包裹的組件在切換時不會被銷毀,而是緩存到內存中並執行 deactived 鈎子函數,命中緩存渲染后會執行 actived 鈎子函數。
props
- include - 字符串或正則表達,只有匹配的組件會被緩存
- exclude - 字符串或正則表達式,任何匹配的組件都不會被緩存
-
// 組件 a
-
export default {
-
name: 'a',
-
data () {
-
return {}
-
}
-
}
-
<keep-alive include="a">
-
<component>
-
<!-- name 為 a 的組件將被緩存! -->
-
</component>
-
</keep-alive>可以保留它的狀態或避免重新渲染
-
<keep-alive exclude="a">
-
<component>
-
<!-- 除了 name 為 a 的組件都將被緩存! -->
-
</component>
-
</keep-alive>可以保留它的狀態或避免重新渲染
但實際項目中,需要配合vue-router共同使用
App.vue
-
<template>
-
<div id="app">
-
<!-- 路由占位符 -->
-
<!-- <router-view></router-view> -->
-
<keep-alive>
-
<router-view v-if="$route.meta.keepAlive">
-
<!-- 這里是會被緩存的視圖組件 -->
-
</router-view>
-
</keep-alive>
-
-
<router-view v-if="!$route.meta.keepAlive">
-
<!-- 這里是不被緩存的視圖組件 -->
-
</router-view>
-
</div>
-
</template>
router -> index.js
-
const routes = [
-
{ path: '/', redirect: '/index' },
-
{ path: '/', redirect: '/home' },
-
{
-
path: '/home',
-
component: HomeLayout,
-
children: [
-
{
-
path: '/home',
-
component: Home
-
},
-
{
-
path: '/workingCondition',
-
component: () =>
-
import(
-
/*webpackChunkName:"workingCondition"*/ '../views/workingCondition/index.vue'
-
),
-
meta: {
-
keepAlive: true // 需要被緩存
-
}
-
}
-
]
-
},
-
{
-
path: '/reportView',
-
component: () => import('../views/other/reportView.vue')
-
},
-
{
-
path: '/todo',
-
component: () => import(/*webpackChunkName:"ToDo"*/ '../views/ToDo.vue'),
-
meta: {
-
keepAlive: true // 需要被緩存
-
}
-
}
-
]
轉:https://blog.csdn.net/qq_37548296/article/details/110798890