Vue 3 的 Composition API 提供了一种新的方式来组织你的组件逻辑。这种方式比传统的 Options API 更具可读性、可维护性和重用性。以下是如何使用 Vue 3 的 Composition API 的基本步骤:
- 安装 Vue 3
如果你还没有安装 Vue 3,你可以通过 npm 或 yarn 来安装它:
npm install vue@next
# 或者
yarn add vue@next
- 创建组件
在你的 Vue 组件中,你可以使用 setup
函数来访问 Composition API 的功能。setup
函数在 beforeCreate
和 created
钩子之前运行,并作为组件的入口点。
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'MyComponent',
setup() {
// 使用 ref 创建一个响应式引用
const count = ref(0);
// 定义一个方法
const increment = () => {
count.value++;
};
// 返回需要在模板中使用的响应式引用和方法
return {
count,
increment,
};
},
};
</script>
- 使用其他 Composition API 函数
Composition API 提供了许多有用的函数,如 reactive
、computed
、watch
等。你可以根据需要在你的组件中使用它们。
* `reactive`:用于创建响应式对象。
* `computed`:基于其他响应式引用或计算属性创建一个新的计算属性。
* `watch`:侦听一个响应式引用或计算属性的变化,并在其变化时运行一个回调函数。
以下是一个使用 reactive
和 computed
的示例:
<template>
<div>
<p>{{ fullName }}</p>
<p>{{ reversedName }}</p>
</div>
</template>
<script>
import { reactive, computed } from 'vue';
export default {
name: 'MyComponent',
setup() {
// 使用 reactive 创建一个响应式对象
const state = reactive({
firstName: 'John',
lastName: 'Doe',
});
// 创建一个计算属性,它基于 state.firstName 和 state.lastName
const fullName = computed(() => {
return `${state.firstName} ${state.lastName}`;
});
// 另一个计算属性,它反转 fullName 的值
const reversedName = computed(() => {
return fullName.value.split('').reverse().join('');
});
// 返回需要在模板中使用的响应式属性和计算属性
return {
fullName,
reversedName,
};
},
};
</script>
- 使用
provide
和inject
provide
和 inject
可以让你在祖先组件和后代组件之间传递依赖项,而无需层层传递 props。这对于实现可复用的插件、高阶组件或具有类似特性的代码段特别有用。
// 祖先组件
export default {
setup() {
const theme = ref('dark');
provide('theme', theme);
// ...
},
};
// 后代组件
export default {
setup() {
const theme = inject('theme', 'light'); // 如果没有提供 'theme',则返回 'light'
// ...
},
};
- 使用 TypeScript
Composition API 与 TypeScript 配合得非常好,因为它鼓励你将组件的逻辑分解为独立的、可重用的函数。这些函数可以具有明确的输入和输出类型,从而提高了代码的可读性和可维护性。
总之,Vue 3 的 Composition API 提供了一种更加灵活和强大的方式来组织你的组件逻辑。通过学习和使用这些新的 API,你可以构建出更加可维护、可重用和可测试的 Vue 组件。