我喜欢在特定的Piniastore 执行大量查询的 idea ,因为我可以在代码中的任何地方重用这些函数,但我正在努力实现它.我有以下Piniastore 来购买产品:
//using composition api in Pinia
import { ref } from 'vue';
import { defineStore } from 'pinia';
export const useProductStore = defineStore('product', () => {
const config = useRuntimeConfig();
const isLoading = ref(false);
const getProductData = async (id) => {
isLoading.value = true
try {
const query = gql`
query GetProductsById($id: ID!) {
product(id: $id) {
id
title
vendor
publishedAt
handle
variants(first: 100) {
nodes {
id
title
price {
amount
}
image {
url
altText
width
height
}
}
}
}
}
`
const variables = {
id: "gid://shopify/Product/" + id,
}
var results = await useAsyncQuery(query, variables);
isLoading.value = false
return results
} catch {
isLoading.value = false
return null
}
};
return {getProductData, isLoading};
});
然后,在我的产品页面中,我try 实现以下内容以显示结果:
<template>
<div class="bg-white">
{{ JSON.stringify(product.value) }}
</div>
</template>
<script setup>
import { ref } from 'vue'
import { storeToRefs } from 'pinia';
import { useProductStore } from '../stores/product-store';
import {useRoute } from 'vue-router'
const route = useRoute();
const productStore = useProductStore();
const { isLoading } = storeToRefs(productStore);
const product = computed(() => {
if (isLoading.value == true) {
return null;
} else {
return productStore.getProductData(route.query.id);
}
});
</script>
我这样做,null总是显示在屏幕上,但是我认为计算(computed)属性是react 性的,一旦函数完成,它应该显示我的数组的值.我确实try 了console.log(productStore.getProductData(route.query.id)),它将返回promise并显示目标中的数据.我也很不好用JavaScript中的javascript/await,所以我不知道这里出了什么问题.