【问题标题】:Prevent graphql query in vue-apollo if input variable is null如果输入变量为空,则阻止 vue-apollo 中的 graphql 查询
【发布时间】:2019-09-22 18:06:57
【问题描述】:

我一直在做一些阅读,并提出了一个联系人输入字段的查询设置。我想避免在组件启动时使用空输入运行此查询。我也许可以通过计算方法手动运行查询,但是有没有一种简单的方法来防止这种情况?

apollo: {
    search: { 
        query: () => contactSearchGQL,
        variables() { 
            return { 
                searchText: this.searchText, 
            };
        },
        debounce: 300,
        update(data) { 
            console.log("received data: " + JSON.stringify(data));
        },
        result({ data, loading, networkStatus }) {
            console.log("We got some result!")
        },
        error(error) {
            console.error('We\'ve got an error!', error)
        },
        prefetch() { 
            console.log("contact search, in prefetch");
            if ( this.searchText == null ) return false;
            return true;
        },
    },
},

我想我不了解预取,或者它是否适用于这里?

【问题讨论】:

    标签: vuejs2 graphql vue-apollo


    【解决方案1】:

    您应该为此使用skip 选项,如the docs 所示:

    apollo: {
      search: { 
        query: () => contactSearchGQL,
        variables() { 
          return { 
            searchText: this.searchText, 
          };
        },
        skip() {
          return !this.searchText;
        },
        ...
      },
    },
    

    searchText 随时更新,skip 将重新评估 -- 如果评估结果为 false,则将运行查询。如果您需要在组件的其他地方控制此逻辑,也可以直接设置 skip 属性:

    this.$apollo.queries.search.skip = true
    

    prefetch 选项特定于 SSR。默认情况下,vue-apollo 将预取服务器端渲染组件中的所有查询。将 prefetch 设置为 false 会为特定查询禁用此功能,这意味着特定查询在组件呈现在客户端上之前不会运行。这并不意味着跳过查询。有关vue-apollo 中的 SSR 的更多详细信息,请参阅here

    【讨论】:

      【解决方案2】:

      阿波罗客户端

      const { loading, error, data } = useQuery(GET_SOME_DATA_QUERY, {
          variables: { param1 },
          skip: param1 === '',
        })
      

      只有当 param1 不为空时才会触发此查询。

      【讨论】:

        猜你喜欢
        • 2018-03-02
        • 2020-11-02
        • 2018-11-12
        • 1970-01-01
        • 2018-02-01
        • 2017-11-18
        • 2021-06-13
        • 1970-01-01
        • 2020-05-18
        相关资源
        最近更新 更多