代码之家  ›  专栏  ›  技术社区  ›  r3plica

vue2 composition api为什么watch不开火

  •  0
  • r3plica  · 技术社区  · 3 年前

    我希望这很简单。 我有一个名为“品牌”的组件,它的代码如下所示:

    import {
      computed,
      defineComponent,
      getCurrentInstance,
      ref,
      toRefs,
      watch,
    } from "@vue/composition-api";
    
    import { useTrackProductImpressions } from "@logic/track-product-impressions";
    import BrandComponent from "@components/brand/brand.component.vue";
    import { Brand } from "@/_core/models";
    
    export default defineComponent({
      name: "Brands",
      components: { BrandComponent },
      emits: ["onMore"],
      props: {
        brands: {
          type: Array,
          required: false,
          default: () => [],
        },
        hasMoreResults: {
          type: Boolean,
          required: false,
        },
        itemsToShow: {
          type: Number,
          required: false,
        },
        loading: {
          type: Boolean,
          required: false,
        },
        total: {
          type: Number,
          required: false,
        },
      },
      setup(props) {
        const instance = getCurrentInstance();
        const { itemsToShow, brands } = toRefs(props);
        const count = ref(0);
        const skip = computed(() => {
          if (!itemsToShow.value) return 0;
          return count.value * itemsToShow.value;
        });
    
        const more = () => {
          count.value++;
          instance.proxy.$emit("onMore");
        };
    
        console.log(brands);
    
        watch(brands, (impressions: Brand[]) => {
          console.log(impressions);
          if (!impressions.length) return;
          const route = instance.proxy.$route;
          useTrackProductImpressions(impressions, route);
        });
    
        return {
          skip,
          more,
        };
      },
    });
    

    正如你所看到的,我已经建立了一个 品牌 属性,以便在定义它时跟踪它。问题是,它永远不会被调用。 第一个控制台日志,我可以看到brands ref,可以看到它的值是一个数组,但在watch方法中,它从未被调用。

    在没有品牌的情况下,组件永远不会初始化:

    <brands
      :brands="brands"
      :hasMoreResults="brandsHasMoreResults"
      :itemsToShow="brandsItemsToShow"
      :total="brandsTotal"
      @onMore="brandsFetchMore()"
      v-if="brands.length"
    />
    

    如有任何帮助,我们将不胜感激。

    0 回复  |  直到 3 年前