【问题标题】:vue apollo useQuery, how to return the result?vue apollo useQuery,如何返回结果?
【发布时间】:2021-06-23 09:15:57
【问题描述】:

我正在尝试使用 @vue/apollo-composable 将 useQuery 与 Vue 2 一起使用。

这是我的设置函数:

setup(props,ctx){
  const product = ref(null);
  const param = usePram();
  const currentProduct = computed(()=>product?.value?.prop || {nope:true};
  const getProduct = () => {
    if(sku.value){
      product.value = provideApolloClient(apolloClient)(() => useQuery(
        gql`the query`,
        {
          param: param.value,
        }
      )).result;
    }
  };
  watch(
    [param],
    ()=>{
      getProduct();
    }
  );
  watch(product,()=>{
    //product.value.value is undefined now
    console.log('product changed:',product.value,product.value?.value)
    //later when I run window.product.value.product.id in the console
    //  I get the id of the product
    window.product = product.value;
  })
  onMounted(getProduct);
  return { currentProduct:currentProduct.value }
},

模板:

<div class="row no-gutters">
  <pre>{{JSON.stringify(currentProduct,undefined,2)}}</pre>
</div>

它只显示{nope: true} 并且产品上的手表只执行一次说product.value?.value 未定义但运行window.product.value.product.id 给了我产品ID,所以我猜它什么时候记录它还没有设置,什么时候设置它不再运行手表。

我想知道如何从观看 arg 的手表中获取产品价值并将其返回,以便我可以在视图中使用它。

【问题讨论】:

    标签: vue.js vuejs2 vue-composition-api vue-apollo


    【解决方案1】:

    尝试添加deep:true 选项,因为被监视的属性是一个对象:

      watch(product,()=>{
        //product.value.value is undefined now
        console.log('product changed:',product.value,product.value?.value)
        //later when I run window.product.value.product.id in the console
        //  I get the id of the product
        window.product = product.value;
      },{deep:true})
    

    【讨论】:

      【解决方案2】:

      我可以通过嵌套手表获得它:

        const getProduct = () => {
          if(sku.value){
            const result = provideApolloClient(apolloClient)(() => useQuery(
              gql`the query`,
              {
                param: param.value,
              }
            )).result;
            watch(result,(result)=>product.value=result);
          }
        };
      

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 2020-11-02
        • 2020-11-08
        • 2020-03-27
        • 2020-11-08
        • 2021-08-26
        • 2020-12-14
        • 2020-01-02
        • 1970-01-01
        相关资源
        最近更新 更多