<keep-alive>
包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
当组件在 <keep-alive>
内被切换,它的 activated
和 deactivated
这两个生命周期钩子函数将会被对应执行。
也就是activated
和 deactivated
必要和<keep-alive>配套使用才会生效。
而当组件使用keep-alive的时候created钩子函数只会被执行一次。
注意:当在activated钩子里面使用axios调用接口的时候且activated钩子里面的参数没有任何的改动的时候axios调用的接口只会被执行一次。如果activated里面的相关参数发生变化的时候axios调用的接口会被再一次执行(找不到相关的文档资料说明,求链接)。这个特性可以用来减少接口的调用。
示例代码:
创建一个A组件(E:\webProjiect\vuetest\test\src\components\A\index.vue)
<template>
<div>
<h1>我是A组件</h1>
</div>
</template>
<script>
export default {
name: "index",
created(){
console.log("created");
},
activated(){
console.log("activated");
},
deactivated(){
console.log("deactivated");
}
}
</script>
<style scoped>
</style>
创建一个B组件(E:\webProjiect\vuetest\test\src\components\B\index.vue)
<template>
<div>
<h1>我是B组件</h1>
</div>
</template>
<script>
export default {
name: "index"
}
</script>
<style scoped>
</style>
修改App.vue文件
<template>
<div id="app">
<router-link to="/a">切换到a</router-link>
<span>-----</span>
<router-link to="/b">切换到b</router-link>
<keep-alive>
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
修改mian.js文件
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import A from './components/A'
import B from './components/B'
Vue.use(VueRouter)
Vue.config.productionTip = false
const routes = [
{ path: '/a', component: A },
{ path: '/b', component: B }
]
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
})
new Vue({
render: h => h(App),
router
}).$mount('#app')
当第一次点击切换到A的时候,调用了A组件的create和activeted钩子
点击切换到B的时候执行了deactivated钩子函数
点击切换到A的时候执行了activeted钩子函数