Vue生命周期与Hook

2024-08-20

Vue 生命周期 & Hook

1. Options API 生命周期

Hook 名称 时机
beforeCreate 实例初始化之后,数据观测与事件配置之前
created 实例已创建,数据观测和方法可用
beforeMount 模板编译前,挂载之前
mounted 挂载完成,DOM 可操作
beforeUpdate 数据变化,但 DOM 未更新
updated 数据变化,DOM 更新完成
beforeUnmount 卸载之前
unmounted 卸载完成

2. Composition API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref, reactive, onMounted, watch } from 'vue';

export default {
setup(props) {
const count = ref(0);
const state = reactive({ name: 'Vue' });

onMounted(() => {
console.log('组件已挂载');
});

watch(() => state.name, (newVal, oldVal) => {
console.log(newVal, oldVal);
});

return { count, state };
}
}

3. Props 与事件传参

父传子

1
<Child :propData="msg" />
1
props: ['propData']

子传父

1
2
3
4
5
6
// 子组件
this.$emit('update', value)

// 父组件
<Child @update="handleUpdate" />
methods: { handleUpdate(val) { console.log(val) } }

v-model 双向绑定 (Vue3)

1
<Child v-model:count="parentCount" />