如果输入变量为 null,则阻止 vue-apollo 中的 graphql 查询

Chr*_*s K 1 graphql vuejs2 vue-apollo

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

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;
        },
    },
},
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*den 8

您应该利用skip该选项,如文档中所示:

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

任何时候searchText更新,skip都会重新评估——如果评估结果为 false,则将运行查询。如果您需要在组件中的其他位置控制此逻辑,您还可以直接设置skip属性:

this.$apollo.queries.search.skip = true
Run Code Online (Sandbox Code Playgroud)

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