以下是 Vue 3 中 nextTick
、onMounted
、reactive
和 ref
的详细说明、代码示例及总结表格:
1. nextTick
作用
在 Vue 完成 DOM 更新后执行回调函数。
适用场景:当修改响应式数据后,需要确保 DOM 已更新时执行操作(如操作 DOM 元素)。
代码示例
<template>
<div ref="myDiv">Hello Vue!</div>
<button @click="updateText">Update Text</button>
</template>
<script setup>
import { ref, nextTick } from 'vue';
const myDiv = ref(null);
const updateText = () => {
// 修改 DOM 内容
myDiv.value.textContent = 'Updated!';
// 使用 nextTick 确保 DOM 更新后再操作
nextTick(() => {
console.log('DOM updated:', myDiv.value.offsetHeight); // 获取更新后的高度
});
};
</script>
2. onMounted
作用
Vue 的生命周期钩子,在组件挂载完成后执行。
适用场景:初始化操作(如数据获取、事件监听、第三方库初始化)。
代码示例
<template>
<div>Data: {{ data }}</div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
const data = ref('');
onMounted(() => {
// 模拟 API 请求
fetch('https://api.example.com/data')
.then(res => res.json())
.then(result => {
data.value = result;
});
});
</script>
3. reactive
作用
创建一个响应式对象,当对象属性变化时,依赖它的视图会自动更新。
适用场景:管理复杂对象的响应式状态。
代码示例
<template>
<div>
<p>Name: {{ user.name }}</p>
<p>Age: {{ user.age }}</p>
<button @click="updateUser">Update User</button>
</div>
</template>
<script setup>
import { reactive } from 'vue';
const user = reactive({
name: 'Alice',
age: 25
});
const updateUser = () => {
user.name = 'Bob';
user.age = 30;
};
</script>
4. ref
作用
创建一个响应式引用值,用于管理基本类型或单个值的响应式状态。
适用场景:管理单个值(如数字、布尔值、元素引用)。
代码示例
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => {
count.value++; // 通过 .value 访问和修改值
};
</script>
总结表格
函数 | 作用 | 使用场景 | 示例代码片段 |
---|---|---|---|
nextTick | 在 DOM 更新后执行回调 | 操作更新后的 DOM 元素 | nextTick(() => console.log(element.offsetHeight)) |
onMounted | 组件挂载完成后执行初始化逻辑 | 数据获取、事件监听、DOM 操作 | onMounted(() => fetch('api').then(setData)) |
reactive | 创建响应式对象,管理复杂对象状态 | 管理对象或数组的响应式数据 | const user = reactive({ name: 'Alice', age: 25 }) |
ref | 创建响应式引用值,管理单个基本类型值 | 管理单个值(如计数器、布尔标志) | const count = ref(0); count.value++ |
关键区别
-
reactive
vsref
:reactive
用于对象/数组,返回代理对象,直接访问属性(如user.name
)。ref
用于单个值,返回引用对象,需通过.value
访问(Vue 3.2+ 支持解构时自动展开)。
-
nextTick
的必要性:- Vue 的更新是异步的,直接操作 DOM 可能获取不到最新值,需通过
nextTick
确保 DOM 更新完成。
- Vue 的更新是异步的,直接操作 DOM 可能获取不到最新值,需通过
-
onMounted
的优势:- 替代 Vue 2 的
mounted
生命周期钩子,更符合组合式 API 的逻辑复用需求。
- 替代 Vue 2 的
如果需要进一步了解具体场景或代码细节,请随时提问!