3️⃣ 函数内部把组件中需要用到的 数据 或者 方法 return 出去;
import { ref, onMounted } from 'vue';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { getCategoryListAPI } from "@/apis/category";
export const useCategory = () => {
const categoryList = ref([]);
const categoryName = ref("");
const route = useRoute();
const getCategoryList = async (id = route.params.id) => {
const {
code,
result: { children, name },
} = await getCategoryListAPI({ id });
if (code != 1) return (categoryList.value = []);
categoryList.value = children;
categoryName.value = name;
};
onMounted(() => getCategoryList());
onBeforeRouteUpdate((to) => {
getCategoryList(to.params.id);
});
return {
categoryList,
categoryName
}
}