生命周期钩子#
每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模板,挂载实例到 DOM,以及在数据改变时更新 DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。
生命周期图示
有关所有生命周期钩子及其各自用例的详细信息,请参考生命周期钩子 API 索引。
注册周期钩子
会在实例生命周期的不同阶段被调用,最常用的是 mounted、updated 和 unmounted。
import Foo from './Foo.vue'
import Bar from './Bar.vue'
export default {
components: { Foo, Bar },
data() {
return {
view: 'Foo'
}
},
computed: {
// 一个计算属性的 getter
publishedBooksMessage() {
// `this` 指向当前组件实例
return this.author.books.length > 0 ? 'Yes' : 'No'
}
},
watch: {
// 每当 question 改变时,这个函数就会执行
name(newQuestion, oldQuestion) {
// ...
}
},
beforeCreate() {
},
created() {
console.log(`the component is now mounted.`)
},
mounted() {
},
beforeUnmount() {
},
methods() {
hadler1() {
},
hadler2() {
}
},
}
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeUnmount
- unmounted