2020版
根据视频整理,链接: 视频链接
P31—生命周期1
一般请求网络数据等操作要么在created(组件初始化之前)要么在mounted(组件初始化之后)
P32—生命周期2
在方框对应位置是初始化数据和方法
所以对应的执行顺序如下:
export default {
name: 'LifeCircle',
beforeCreate () {
console.log('1.beforeCreate')
},
data () {
return {
isShow: false,
str1: 'str-----',
str2: 'str====='
}
},
methods: {},
created () {
console.log('2.created')
},
beforeMount () {
console.log('3.beforeMount')
},
mounted () {
console.log('4.mounted')
// 定时器
setInterval(() => {
console.log('+++++++++++++++++++++')
this.isShow = !this.isShow
}, 1000)
},
beforeUpdate () {
console.log('5.beforeUpdate')
},
updated () {
console.log('6.updated')
},
beforeDestroy () {
console.log('7.beforeDestroy')
},
destroyed () {
console.log('8.destroyed')
}
}
写个小demo看看执行了哪些
<template>
<div>
<p v-if='isShow'>{{str1}}</p> <!--这里注意isShow一定要加引号-->
<p v-else>{{str2}}</p>
</div>
</template>
执行打印出:
下面测试销毁:注册一个事件
methods: {
destroy () {
// 销毁一个实例或者当前组件,直接用this
this.$destroy()
}
}
点击之后,所有周期走完,但是定时器没有被清掉
销毁时要格外注意清除定时器
- 给定时器加id,为了拿到,要加this.
this.interId = setInterval(() => {
console.log('+++++++++++++++++++++')
this.isShow = !this.isShow
}, 1000)
2.在beforeDestroy里面把定时器的id给clearxxx
beforeDestroy () {
console.log('7.beforeDestroy')
// 清除定时器
clearInterval(this.interId)
}
此时:
汇总以上代码:
1-在LifeCircle.vue中的代码:
<template>
<div>
<p v-if='isShow'>{{str1}}</p>
<p v-else>{{str2}}</p>
<button @click='destroy'>销毁</button>
</div>
</template>
<script>
export default {
name: 'LifeCircle',
beforeCreate () {
console.log('1.beforeCreate')
},
data () {
return {
isShow: false,
str1: 'str-----',
str2: 'str====='
}
},
methods: {
destroy () {
// 销毁一个实例或者当前组件,直接用this
this.$destroy()
}
},
created () {
console.log('2.created')
},
beforeMount () {
console.log('3.beforeMount')
},
mounted () {
console.log('4.mounted')
// 定时器
this.interId = setInterval(() => {
console.log('+++++++++++++++++++++')
this.isShow = !this.isShow
}, 1000)
},
beforeUpdate () {
console.log('5.beforeUpdate')
},
updated () {
console.log('6.updated')
},
beforeDestroy () {
console.log('7.beforeDestroy')
// 清除定时器
clearInterval(this.interId)
},
destroyed () {
console.log('8.destroyed')
}
}
</script>
<style scoped>
</style>
2-在App.vue中的代码(注意第三行)
<template>
<div id="app">
<LifeCircle/>
</div>
</template>
<script>
import LifeCircle from './components/LifeCircle'
export default {
name: 'App',
components: {
LifeCircle
}
}
</script>
<style>
</style>