Vue 3 的核心组合式 API 函数及其完整示例、使用场景和总结表格
以下是 Vue 3 的核心组合式 API 函数及其完整示例、使用场景和总结表格:
1. 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>
2. 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>
3. computed
作用
创建一个计算属性,基于响应式数据动态计算值。
示例
<template><div><p>First: {{ firstName }}</p><p>Last: {{ lastName }}</p><p>Full Name: {{ fullName }}</p></div>
</template><script setup>
import { ref, computed } from 'vue';const firstName = ref('John');
const lastName = ref('Doe');const fullName = computed(() => {return `${firstName.value} ${lastName.value}`;
});
</script>
4. watch
作用
监视响应式数据的变化,并在变化时执行回调。
示例
<template><div><input v-model="message" placeholder="输入内容..." /><p>输入内容变化次数:{{ changeCount }}</p></div>
</template><script setup>
import { ref, watch } from 'vue';const message = ref('');
const changeCount = ref(0);watch(message, (newValue, oldValue) => {changeCount.value++;
});
</script>
5. watchEffect
作用
自动追踪响应式依赖,并在依赖变化时执行回调(无需手动指定依赖项)。
示例
<template><div><input v-model="text" placeholder="输入内容..." /><p>输入内容反转:{{ reversedText }}</p></div>
</template><script setup>
import { ref, watchEffect } from 'vue';const text = ref('');
let reversedText = '';watchEffect(() => {reversedText = text.value.split('').reverse().join('');
});
</script>
6. onMounted
作用
在组件挂载完成后执行初始化逻辑(生命周期钩子)。
示例
<template><div ref="myDiv">Hello Vue!</div>
</template><script setup>
import { ref, onMounted } from 'vue';const myDiv = ref(null);onMounted(() => {console.log('Component mounted:', myDiv.value.offsetHeight);
});
</script>
7. nextTick
作用
在 Vue 完成 DOM 更新后执行回调。
示例
<template><div ref="box">Click to change color</div><button @click="changeColor">Change Color</button>
</template><script setup>
import { ref, nextTick } from 'vue';const box = ref(null);const changeColor = () => {box.value.style.backgroundColor = 'lightblue';nextTick(() => {console.log('DOM updated:', box.value.style.backgroundColor);});
};
</script>
8. provide
& inject
作用
实现祖先进级通信,父组件提供数据,子组件注入使用。
示例
父组件(Parent.vue):
<template><ChildComponent />
</template><script setup>
import { provide, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';const theme = ref('light');
provide('theme', theme);
</script>
子组件(ChildComponent.vue):
<template><div :class="theme.value">当前主题:{{ theme.value }}</div>
</template><script setup>
import { inject } from 'vue';const theme = inject('theme');
</script>
9. toRefs
作用
将 reactive
对象的属性转换为独立的 ref
引用,避免解构后失去响应性。
示例
<template><div><p>Name: {{ name }}</p><p>Age: {{ age }}</p></div>
</template><script setup>
import { reactive, toRefs } from 'vue';const state = reactive({name: 'Alice',age: 25
});// 使用toRefs保持响应性
const { name, age } = toRefs(state);
</script>
10. shallowReactive
& shallowRef
作用
创建浅层响应式对象/引用,仅追踪顶级属性变化。
示例
<template><div><p>{{ obj.name }}</p><p>{{ obj.detail }}</p></div>
</template><script setup>
import { shallowReactive } from 'vue';const obj = shallowReactive({name: 'Item',detail: { price: 100 }
});// 修改顶级属性会触发更新
obj.name = 'New Item'; // 修改嵌套属性不会触发更新(需使用reactive)
obj.detail.price = 200; // 不会触发视图更新
</script>
总结表格
函数 | 作用 | 示例代码片段 | 使用场景 |
---|---|---|---|
ref | 创建响应式引用值(基本类型或单值) | const count = ref(0); count.value++ | 管理单个值(如计数器、布尔标志) |
reactive | 创建响应式对象或数组 | const user = reactive({ name: 'Alice' }); user.name = 'Bob' | 管理复杂对象/数组的响应式状态 |
computed | 定义计算属性(基于响应式数据动态计算值) | const fullName = computed(() => firstName.value + lastName.value) | 需要动态计算值时(如合并多个响应式值) |
watch | 监听响应式数据变化并执行回调 | watch(message, (newVal) => console.log(newVal)) | 需要响应数据变化时执行副作用(如日志、API请求) |
watchEffect | 自动追踪依赖并响应变化 | watchEffect(() => console.log(text.value)) | 需要自动追踪依赖项的副作用(无需手动指定依赖) |
onMounted | 组件挂载后执行逻辑(生命周期钩子) | onMounted(() => console.log('Mounted!')) | 初始化操作(如数据获取、DOM操作) |
nextTick | 在 DOM 更新后执行回调 | nextTick(() => console.log(element.offsetHeight)) | 需要操作更新后的 DOM 元素 |
provide/inject | 祖先进级通信(父组件提供数据,子组件注入使用) | provide('theme', theme) 和 const theme = inject('theme') | 需要在多层组件间共享数据 |
toRefs | 将 reactive 对象的属性转为 ref,保持响应性 | const { name } = toRefs(state) | 解构 reactive 对象后仍需保持响应性 |
shallowReactive | 创建浅层响应式对象(仅追踪顶级属性) | const obj = shallowReactive({ name: 'Item' }) | 管理嵌套层级较深的对象,优化性能 |
关键区别
对比项 | ref | reactive | watch | watchEffect |
---|---|---|---|---|
适用类型 | 基本类型、单个值 | 对象、数组 | 任何响应式数据 | 自动追踪依赖 |
访问方式 | .value | 直接访问属性 | 需指定依赖项 | 无需指定依赖项 |
响应性深度 | 深响应 | 深响应 | 支持嵌套属性变化 | 支持嵌套属性变化 |
如果需要其他函数(如 onUnmounted
、getCurrentInstance
等)的示例或进一步解释,请随时告知!