每个Vue实例在被创建时都要经过一系列的初始化过程,例如:需要设置数据监听、编译模板、将实例挂载到DOM并在数据变化时,更新DOM等,这些都称为Vue实例的生命周期。
3.1使用生命周期钩子
在VUE实例的生命周期过程中会运行一些叫做生命周期的钩子函数,这给用户在不同阶段添加自己代码的机会
<template>
<div id="app">
<p v-if="courses.length==0">没有任何课程信息</p>
<ul>
<li v-for="(item,index) in courses" :key=index>{{item}}</li>
</ul>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
courses:[],
}
}
methods:{
getCourses(){
return new Promise(resolve=>{
setTimeout(()=>{
resolve(['web全栈','Web高级'])
},2000)
})
}
},
async created(){
const courses =await this.getCourses();
console.log(courses)
this.courses = courses
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
3.2探讨生命周期
<template>
<div id="app">
<!-- 生命周期 -->
<h1>初始化流程</h1>
<p>{{foo}}</p>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
foo:'foo'
}
},
beforeCreate(){
console.log("beforeCreate")
},
created(){
console.log('created'+this.$el)
},
beforeMount(){
console.log('beforeMount')
},
mounted(){
setTimeout(()=>{
this.foo ="foooo"
},2000)
console.log('mounted',this.$el)
},
beforeUpdate(){
console.log('beforeUpdate')
},
updated(){
console.log('updated')
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
生命周期分为三个阶段:初始化、更新、销毁
初始化:beforeCreate、created、beforeMount、mounted
更新:beforeUpdate、updated
销毁:beforeDestroy、destroyed
使用场景分析:
beforeCreate(){}//执行时,组件实例还没创建,通常用于插件开发中执行一些初始化任务
created(){}//组件初始化完毕,各种数据可以使用,通常用于异步数据获取
beforeMounted(){}//未执行渲染、更新,dom未创建
mounted(){}//初始化结束,dom创建,可用于访问数据和dom元素
beforeUpdate(){}//更新前,可用于获取更新前的各种状态
updated(){}//更新后,所有状态已是最新的
beforeDestroy(){}//销毁前,可用于一些定时器或订阅的取消
destoryed(){}//组件已销毁
详细代码地址:https://gitee.com/JingYaBei/study-vue