在 Vue 3 中,setup
函数是 Composition API 的核心部分,它允许你使用响应式状态和其他 Composition API 功能。然而,就像在其他框架中的组件方法或生命周期钩子中一样,setup
函数内定义过多逻辑可能会使代码变得难以阅读和维护。为了解决这个问题,Vue 3 开发者通常会将相关逻辑封装成自定义的 Composition API 函数(有时也称为“自定义 Hooks”,尽管这个术语更多地在 React 社区中使用)。
在 Vue 3 中,这些自定义函数通常被称为“composables”。它们允许你将逻辑从 setup
函数中提取出来,放到单独的、可重用的文件中,从而提高代码的可读性和可维护性。
以下是一个 Vue 3 中使用 composables 的示例:
示例:封装数据获取逻辑到 composable
假设我们有一个组件需要从 API 获取数据并在模板中显示这些数据。
<template><div><h1>Data from API</h1><div v-if="loading">Loading...</div><div v-else-if="error">{{ error }}</div><div v-else>{{ data }}</div></div>
</template><script>
import { ref, onMounted } from 'vue';
import axios from 'axios';export default {setup() {const data = ref(null);const loading = ref(true);const error = ref(null);const fetchData = async () => {try {const response = await axios.get('https://api.example.com/data');data.value = response.data;} catch (err) {error.value = err.message;} finally {loading.value = false;}};onMounted(fetchData);return {data,loading,error,};},
};
</script>
封装成 composable
我们将数据获取逻辑封装到一个名为 useFetchData
的 composable 中:
// useFetchData.js
import { ref, onMounted } from 'vue';
import axios from 'axios';export function useFetchData(url) {const data = ref(null);const loading = ref(true);const error = ref(null);const fetchData = async () => {try {const response = await axios.get(url);data.value = response.data;} catch (err) {error.value = err.message;} finally {loading.value = false;}};onMounted(fetchData);return {data,loading,error,};
}
然后在组件中使用这个 composable:
<template><div><h1>Data from API</h1><div v-if="loading">Loading...</div><div v-else-if="error">{{ error }}</div><div v-else>{{ data }}</div></div>
</template><script>
import { useFetchData } from './useFetchData';export default {setup() {const { data, loading, error } = useFetchData('https://api.example.com/data');return {data,loading,error,};},
};
</script>
通过这种方式,我们将数据获取逻辑从组件的 setup
函数中提取出来,放到了一个可重用的 composable 中。这不仅提高了代码的可读性,还使得这个逻辑可以在其他组件中轻松复用。