Vue.js 的生命周期
介绍
生命周期钩子是一些特殊方法,或者说是窥视孔,让我们能够了解库(React)或框架(Vue)幕后的工作原理。这些方法可以让你知道组件在 Vue 实例中何时被创建、添加到 DOM、更新或销毁。
注意:所有生命周期钩子都会自动将其 this 上下文绑定到实例,以便您可以访问数据、计算属性和方法。
钩子
创作钩子
beforeCreate
钩子beforeCreate会在组件初始化时运行。在此期间,不会设置任何数据或方法。
<script>
export default {
beforeCreate() {
console.log('Lifecycle Initialized')
}
}
</script>
在钩子函数创建
期间created,我们可以访问组件的所有响应式数据成员和方法。此时 DOM 尚未挂载。
<script>
export default {
data() {
return {
data: ""
}
},
created() {
this.data = "Created lifecycle called";
}
}
</script>
安装挂钩
beforeMount
钩子beforeMount在组件的初始渲染之前运行,并在模板或渲染函数编译之后运行。
<script>
export default {
beforeMount() {
console.log(`vm.$el has not been created yet`)
}
}
</script>
安装
在mounted钩子函数中,我们可以访问响应式组件和渲染的 DOM(通过 this.$el)。
<script>
export default {
mounted() {
console.log(`At this point, vm.$el has been created and el has been replaced.`);
}
}
</script>
更新钩子
更新前
该beforeUpdate钩子会在组件数据更改后运行,就在 DOM 被修补和重新渲染之前运行。
<script>
export default {
data() {
return {
counter: 0
}
},
created() {
setInterval(() => {
this.counter++
}, 1000)
},
beforeUpdate() {
console.log(this.counter)
}
}
</script>
更新
该updated钩子会在组件数据发生变化且 DOM 重新渲染后运行。
<script>
export default {
data() {
return {
counter: 0
}
},
created() {
setInterval(() => {
this.counter++
}, 1000)
},
updated() {
console.log(`At this point, Virtual DOM has re-rendered and patched.`)
// Fired every second, should always be true
console.log(this.counter);
}
}
</script>
毁灭之钩
销毁前
该beforeDestroy操作会在组件被销毁或移除之前立即执行。此时组件完全存在且功能完好。
<script>
export default {
beforeDestroy() {
console.log(`At this point, watchers, child components, and event listeners have not been teared down yet.`)
}
}
</script>
损毁
destroyed当组件的所有组成部分都被拆除或彻底销毁时,就会触发此钩子。此方法适用于组件内部所有必要的清理工作。
<script>
export default {
destroyed() {
console.log(`At this point, watchers, child components, and event listeners have been torn down.`)
}
}
</script>
想了解更多关于VueJS的信息,请点击这里。
文章来源:https://dev.to/amolikvivian/the-lifecycles-of-vue-js-lhh
