我刚刚发布了我的应用程序,包括一个Nuxt.js前端,一个Strapi CMS和Headless Shopify用于结账管理。要实现全局购物车组件,我需要加载init上的所有产品,如下所示。数据来自CMS。
./plugins/products.js
// Load products on init
export default async ({app}) => {
await app.store.dispatch('shop/products/setProducts');
}./store/products.js
export const actions = {
async setProducts(state) {
const allProducts = await this.$axios.$get('/products');
state.commit('setProducts', allProducts);
},CMS通过GraphQL/阿波罗客户端从Shopify商店前端API获取数据,如下所示:
./管制员/Product.js
async find(ctx) {
let entities;
if (ctx.query._q) {
entities = await strapi.services.product.search(ctx.query);
} else {
entities = await strapi.services.product.find(ctx.query);
}
for (entity of entities) {
const graphId = btoa('gid://shopify/Product/' + entity.shopifyId);
try {
await client.query({
query: gql`
query {
node(id: "${graphId}") {
... on Product {
id
title
productType
variants(first: 250) {
edges {
node {
title
id
availableForSale
sku
priceV2 {
amount
currencyCode
}
compareAtPriceV2 {
amount
currencyCode
}
requiresShipping
selectedOptions {
name
value
}
}
}
}
}
}
}`
}).then((product) => {
entity.shopify = {
id: product.data.node.id,
product_type: product.data.node.id,
variants: product.data.node.variants,
}
});
} catch (e) {
console.log(e);
}
}
return entities.map(entity => sanitizeEntity(entity, {model: strapi.models.product}));
},
},阿波罗设置:
const ApolloClient = require('apollo-boost').default;
const fetch = require('node-fetch');
const {InMemoryCache, gql} = require('apollo-boost');
const client = new ApolloClient({
uri: 'https://santras.myshopify.com/api/graphql',
cache: new InMemoryCache(),
fetch: fetch,
headers: {
'X-Shopify-Storefront-Access-Token': 'e908298c617e035c47c62ae449887b3c'
}
});最大的问题是,从shopify api加载所有产品和变体是非常缓慢的。没有缓存的所有产品的第一个负载需要多达20000ms。缓存之后,/products的每个请求都要花费1.500秒的时间。
现在,许多测试用户正在经历一个很长的加载时间的nuxt应用程序,因为这一点。在有东西显示之前,有一个5到10秒的裸体加载循环。是否有一种方法,可以在插件数据加载时显示内容?
发布于 2021-03-31 18:04:09
尝试查看Nuxt中的取钩。这使得能够获取异步数据。
在组件端,它公开具有以下状态的$fetchState.pending (特别是)的$fetchState,这在抓取正在进行时是正确的。它允许您在等待从API获取数据时放置一些数据。
<template>
<div v-if="$fetchState.pending">Fetching data from Shopify ...</div>
<div v-else>
<div v-for="product in products" ... />
</div>
</template><script>
export default {
data() {
return {
products: []
}
},
async fetch() {
this.products= await strapi.services.product.search(this.query);
}
}
</script>https://stackoverflow.com/questions/66891329
复制相似问题