继上一章如果我们要有四个导航
<keep-alive>
<router-view></router-view>
</keep-alive>
这样写四个导航确实全部可以缓存,但是我要缓存其中俩个怎么办?
<keep-alive :include="['News','Message']">
<router-view></router-view>
</keep-alive>
用一个功能把新的俩个生命周期钩子全引出来
News.vue
<template>
<div>
<h2>你好,欢迎来到News路由组件</h2>
<ul>
<!--写上这段-->
<li :style="{opacity}">欢迎学习Vue</li>
<li>news1 <input type="text"></li>
<li>news2 <input type="text"></li>
<li>news3 <input type="text"></li>
</ul>
</div>
</template>
<script>
export default {
name: 'News',
components:{},
/*写上这段 begin*/
data(){
return{
opacity:1
}
},
beforeDestroy(){
clearInterval(this.timer)//即将被销毁时清除定时器
},
mounted(){
console.log('mounted',this)
this.timer = setInterval(()=>{
console.log('@')//查看定时器是否在运行
this.opacity -= 0.01
if(this.opacity <= 0) this.opacity = 1
},16)
}
/*写上这段 end*/
}
</script>
<style scoped>
</style>
但是如果我们把news
切走,发现定时器还在运行, 我的News组件被我缓存了
如果取消缓存,这样就保存不到数据了,所以缓存还是得留着的,但问题是不触发销毁流程了。
这样就得引出俩个新的生命周期钩子, 而且这俩个生命周期钩子是路由组件独有的
activated(被激活的(激活))
- 1.在案例里面,你是给
News
写的。
那么News
组件从没有出现在你面前变成出现在你面前
,activated
就被调用了,意思就是激活
了
与之对应的deactivated(取消激活(失活))
从News组件切走变成其他组件
那就是失活
编写之前的逻辑
activated(){
console.log('News组件被激活了')
this.timer = setInterval(()=>{
console.log('@')
this.opacity -= 0.01
if(this.opacity <= 0) this.opacity = 1
},16)
},
deactivated(){
console.log('News组件失活了')
clearInterval(this.timer)
},
对于现在的路由组件,这俩个钩子比mounted
和beforDestroy
更有用
官方的生命周期图中有三个生命周期没有在上面
- activated
- deactivated
- nextTick
//当你修改了数据之后,Vue帮你操作完DOM之后,把真实的DOM放入页面了,Vue在帮你调用这个函数
this.$nextTick(function(){
this.$refs.inputTitle.focus()
})
总结
俩个新的生命周期钩子
1.作用: 路由组件所独有的俩个钩子,用于捕获路由组件的激活状态。
2.具体名字:
- 1.
activated
路由组件被激活时触发。 - 2.
deactivated
路由组件失活时触发。