赞
踩
在Vue 3中,Composition API 是一种全新的逻辑复用和代码组织方式,它允许你将组件的逻辑(如响应式状态、计算属性、方法、生命周期钩子等)封装到单独的函数中,从而提高了代码的可复用性和可维护性。以下是如何在Vue 3中使用Composition API的基本步骤:
首先,你需要从 vue
包中引入 defineComponent
和 Composition API 的其他函数(如 ref
, reactive
, computed
, watch
, onMounted
等)。defineComponent
是可选的,但它提供了类型推断和一些额外的运行时检查。
- import {
- defineComponent, ref, computed, onMounted } from 'vue';
setup
函数setup
函数是 Composition API 的入口点。它是一个在组件创建之前被调用的同步函数,用于设置组件的响应式状态、计算属性、方法等。setup
函数会在 beforeCreate
和 created
生命周期钩子之前被调用,并且它是 this
的上下文之外的(即 this
在 setup
中不是组件实例)。
- <script setup lang="ts">
- import { ref, computed, onMounted } from 'vue';
-
- const count = ref(0);
- const doubled = computed(() => count.value * 2);
-
- onMounted(() => {
- console.log('Component is mounted!');
- });
-
- function increment() {
- count.value++;
- }
- </script>
注意:<script setup>
是 Vue 3 引入的语法糖,它提供了一种更简洁的方式来使用 Composition API。它会自动将 setup
函数的返回值暴露给模板,并且你不需要显式地调用 defineComponent
。
在模板中,你可以直接访问 setup
函数中返回的任何响应式状态、计算属性或方法。
- <template>
- <div>
- <p>{
- { count }}</p>
- <p>{
- { doubled }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
使用 ref
或 reactive
来创建响应式状态。ref
用于基本数据类型,而 reactive
用于对象或数组。
- const count = ref(0); // 使用 ref 创建响应式的基本数据类型
- const person = reactive({
- name: 'Alice', age: 30 }); // 使用 reactive 创建响应式的对象
Composition API 提供了与组件生命周期钩子对应的函数,如 onMounted
, onUpdated
, onUnmounted
等。
- onMounted(() => {
-
- // 组件挂载后执行的代码
- });
-
- onUpdated(() => {
-
- // 组件更新后执行的代码
- });
-
- onUnmounted(() => {
-
- // 组件卸载后执行的代码
- });
虽然 Composition API 本身不直接提供类似于 provide
和 inject
的API,但你可以通过 setup
函数的第二个参数(context
)来访问 provide
和 inject
。不过,更常见的做法是使用 Vue 3 提供的 provide
和 inject
函数(这些函数不是 setup
特有的,但可以在 setup
中使用)。
- // 父组件
- setup() {
-
- const theme = ref('dark');
- provide('theme', theme);
- // ...
- }
-
- // 子组件
- setup(props, {
- inject }) {
-
- const theme = inject('theme')!; // 注意:需要类型断言或使用可选链来处理可能的undefined
- // ...
- }
-
- // 或者使用独立的 provide 和 inject 函数
- // setup() {
-
- // const theme = ref('dark');
- // provide('theme', theme);
- // // ...
- // }
-
- // setup(props, context) {
-
- // const theme = inject('theme', 'default-theme'); // 第二个参数是默认值
- // // ...
- // }
请注意,上面的 inject
示例中使用了 !
来进行非空断言,这是因为 TypeScript 无法自动推断 inject
返回值的非空性。如果你不确定注入的值是否存在,你应该使用可选链(?.
)或默认值来处理它。
通过以上步骤,你可以在Vue 3中有效地使用Composition API来构建你的组件。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。