目录
在 Vue 的开发中,生命周期是一个非常重要的概念。本文将结合视频内容,对 Vue2 的生命周期进行详细分析,并探讨在加入 Vue3 以及代码示例的情况下,生命周期的变化。
一、Vue2 生命周期回顾
- 生命周期函数数量:Vue2 中系统自带的生命周期一共有八个,分别为
beforeCreate
、created
、beforeMount
、mounted
、beforeUpdate
、updated
、beforeDestroy
、destroyed
。 - 执行顺序:在 Vue2 中,生命周期函数的执行顺序是固定的,即使在代码中打乱顺序,实际执行时也会按照既定的顺序进行。例如,在组件执行时,会先执行前四个生命周期函数,即
beforeCreate
、created
、beforeMount
、mounted
。 - 数据与节点的出现时机:
- 在
beforeCreate
阶段,this.$data
和this.$el
都为undefined
。 - 在
created
阶段,有了this.$data
,但this.$el
仍为undefined
。 - 在
mounted
阶段,既有this.$data
,又有this.$el
。
- 在
二、Vue2 生命周期实现原理
在 Vue2 的源码底层,已经写好了生命周期函数的执行顺序。通过判断传入的选项对象中的函数类型,依次执行对应的生命周期函数。例如:
if (typeof options.beforeCreate === 'function') {
options.beforeCreate();
}
// 以此类推执行其他生命周期函数
三、Vue3 中的生命周期变化
在 Vue3 中,生命周期函数的名称发生了一些变化:
beforeCreate
改为setup
之前执行的代码。created
改为setup
内部执行的代码,并且可以使用ref
和reactive
来定义响应式数据。beforeMount
和mounted
基本保持不变。beforeUpdate
和updated
也基本保持不变。beforeDestroy
改为onBeforeUnmount
。destroyed
改为onUnmounted
。
四、代码示例
以下是一个 Vue2 的简单组件示例,展示了生命周期函数的使用:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
{{ message }}
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
beforeCreate() {
console.log('beforeCreate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
},
// 其他生命周期函数...
});
</script>
</body>
</html>
在 Vue3 中,可以使用组合式 API 来定义组件,以下是一个示例:
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app"></div>
<script>
const App = {
setup() {
console.log('setup');
const message = ref('Hello Vue3!');
return {
message
};
},
onBeforeMount() {
console.log('onBeforeMount');
},
onMounted() {
console.log('onMounted');
}
// 其他生命周期函数...
};
const app = Vue.createApp(App);
app.mount('#app');
</script>
</body>
</html>
通过以上内容,相信大家对 Vue 的生命周期有了更深入的理解。无论是 Vue2 还是 Vue3,生命周期函数都在组件的不同阶段发挥着重要作用,帮助开发者更好地管理组件的状态和行为。