【发布时间】:2021-09-13 15:39:31
【问题描述】:
我是 Vue 新手,所以不确定这里出了什么问题。 我已经设置了一个从 graphql 调用返回对象的方法,这个方法看起来像这样:
import { useQuery, useResult } from "@vue/apollo-composable";
import * as getCategoryBySlug from "@/graphql/api/query.category.gql";
export function useGetCategory(slug: string) {
const { result, loading, error } = useQuery(getCategoryBySlug, { slug });
const category = useResult(result, null, (data) => data.getCategoryBySlug);
return { category, loading, error };
}
然后在我的组件中,我设置了这个:
import { defineComponent, onMounted, ref } from "@vue/composition-api";
import { useGetCategory } from "@/logic/get-category";
export default defineComponent({
name: "Categories",
setup(_, context) {
const slug = ref(context.root.$route.params.slug);
const result = ref({});
const getCategory = (s) => {
const { category, loading, error } = useGetCategory(s);
result.value = { category, loading, error };
};
onMounted(() => getCategory(slug.value));
return { result };
},
});
我知道这是错误的,因为我想返回 { category, loading, error } 但我不知道如何从 getCategory 方法中分配它。
无论如何,抛开这个问题,现在我想观察 slug 看看它是否会发生变化(通过路由更改),所以我这样做了:
import { defineComponent, onMounted, ref, watch } from "@vue/composition-api";
import { useGetCategory } from "@/logic/get-category";
export default defineComponent({
name: "Categories",
setup(_, context) {
const slug = ref(context.root.$route.params.slug);
const result = ref({});
const getCategory = (s) => {
const { category, loading, error } = useGetCategory(s);
result.value = { category, loading, error };
};
watch(slug, () => getCategory);
onMounted(() => getCategory(slug.value));
return { result };
},
});
这不起作用。它可以编译,但是当我更改路线时,什么也没有发生。该视图仍显示第一个结果。 这是模板:
<template>
<v-container>
<v-row>
<v-col>
{{ result }}
</v-col>
</v-row>
</v-container>
</template>
有人知道我做错了什么吗?
【问题讨论】:
-
watch(slug, () => getCategory);不会在更改时调用getCategory函数,但会返回getCategory函数。试试这个:watch(slug, getCategory);
标签: vuejs2 vue-composition-api