Vue2 组合 API 手表不工作

Vue2 composition API watch is not working

我是 Vue 的新手,所以不确定这里有什么问题。 我已经设置了一个方法,该方法 returns 来自 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 };
      },
    });

我知道这是错误的,因为我想 return { 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>

有谁知道我做错了什么吗?

我在网上四处寻找,发现有一些东西可以让它发挥作用。我这样做了:

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 = (slug) => {
      const { category, loading, error } = useGetCategory(slug);
      result.value = { category, loading, error };
    };

    watch(() => context.root.$route.params.slug, getCategory);
    onMounted(() => getCategory(slug.value));

    return { result };
  },
});