从 Vue 3 组合中的函数内部返回 Apollo useQuery 结果 api

Returning Apollo useQuery result from inside a function in Vue 3 composition api

我在使用 Apollo v4Vue 找到一种从方法内部将结果 returning 结果到我的模板的干净方法时遇到了一些问题3篇作文API.

这是我的组件:

export default {
    components: {
        AssetCreationForm,
        MainLayout,
        HeaderLinks,
        LoadingButton,
        DialogModal
    },

    setup() {
        const showNewAssetModal = ref(false);

        const onSubmitAsset = (asset) => {
            // how do I access result outside the handler function
            const { result } = useQuery(gql`
                  query getAssets {
                    assets {
                        id
                        name
                        symbol
                        slug
                        logo
                    }
                  }
                `)
            };
        }

        return {
            showNewAssetModal,
            onSubmitAsset,
        }
    },

}

当用户单击页面上的按钮时调用 onSubmitAsset

如何 return 使用设置函数中的查询 result 以便能够在模板中访问它?(我不想复制值)

您可以将 useQuery() 移到提交方法之外,如 shown in the docs。如果你想推迟查询获取直到提交方法被调用,你可以通过传递 enabled:false 作为选项(useQuery 的第三个参数)来禁用自动启动:

export default {
  setup() {
    const fetchEnabled = ref(false)
    const { result } = useQuery(gql`...`, null, { enabled: fetchEnabled })

    const onSubmitAsset = (asset) => {
      fetchEnabled.value = true
    }

    return { result, onSubmitAsset }
  }
}

demo