使用场景:
在开发中某些情况我们希望继续保持组件的状态,而不是销毁掉,这个时候我们就可以使用一个内置组件:keep-alive
使用:
通常我们可以配置整个页面缓存或只让特定的某个组件保持缓存信息,配置了keepalive的路由或者组件,只会在页面初始化
的时候执行created->mounted
生命周期,第二次及以后再进入该页面将不会执行改生命周期,而是会去读取缓存信息
1.keep-alive属性
keep-alive有一些属性:
include - string | RegExp | Array。只有名称匹配的组件会被缓存;
exclude - string | RegExp | Array。任何名称匹配的组件都不会被缓存;
max - number | string。最多可以缓存多少组件实例,一旦达到这个数字,那么缓存组件中最近没有被访问的实例会被销毁;
include 和 exclude prop 允许组件有条件地缓存:
(1)二者都可以用逗号分隔字符串、正则表达式或一个数组来表示;
(2)匹配首先检查组件自身的 name 选项
<div>
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<component :is="view" />
</keep-alive>
<!-- RegExp 使用v-bind -->
<keep-alive include="/a|b/">
<component :is="view" />
</keep-alive>
<!-- Array 使用v-bind -->
<keep-alive include="['a','b']">
<component :is="view" />
</keep-alive>
</div>
页面局部刷新
被keepAlive包裹的组件和页面,页面进入时执行的生命周期为:
created->mounted->activated;
其中created->mounted是页面第一次进入才会执行,
activated生命周期在页面每次进入都会执行,特属于keepAlive的一个生命周期,
所以我们把页面每次进来要进行的操作放入该生命周期即可
import {
ref, onActivated, computed } from 'vue'
export default {
name: 'EditMaterials',
setup() {
onActivated(() => {
activeNameTab.value.init()
})
const activeNameTab = ref(null)
return {
activeNameTab,
}
},
}
使用缓存机制之后:
<template>
<div class="comprehensive-table-container">
<el-tabs v-model="activeName">
<el-tab-pane
v-for="(item, i) in getPageTabs"
:key="i"
:label="item.label"
:name="item.name"
/>
</el-tabs>
<keep-alive>
<component :is="component" />
</keep-alive>
</div>
</template>
<script>
import {
ref, computed } from 'vue'
import {
useStore } from 'vuex'
import ConfigureInformation from './configureInformation/index'
import DataStatistics from './dataStatistics/index'
export default {
name: 'MyEnergy',
components: {
ConfigureInformation, DataStatistics },
setup() {
const store = useStore()
const AllTabs = ref([
{
label: '信息配置',
name: 'configureInformation',
permissions: 'configureInformation_btn:tab',
},
{
label: '数据统计',
name: 'dataStatistics',
permissions: 'dataStatistics_btn:tab',
},
])
const getPageTabs = ref([])
AllTabs.value.forEach((item) => {
store.state.user.elements.map((element) => {
if (element.mapping === item.permissions) getPageTabs.value.push(item)
})
})
const activeName = ref(getPageTabs.value[0].name)
const component = computed(() => {
return activeName.value
})
return {
AllTabs,
activeName,
getPageTabs,
component,
}
},
}
</script>
缓存组件的生命周期
对于缓存的组件来说,再次进入时,
我们是不会执行created或者mounted等生命周期函数的:
但是有时候我们确实希望监听到何时重新进入到了组件,何时离开了组件;
这个时候我们可以使用activated 和 deactivated 这两个生命周期钩子函数来监听;