Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Vuex数据获取:如何在不同组件中等待数据_Javascript_Vue.js_Fetch_Nuxtjs - Fatal编程技术网

Javascript Vuex数据获取:如何在不同组件中等待数据

Javascript Vuex数据获取:如何在不同组件中等待数据,javascript,vue.js,fetch,nuxtjs,Javascript,Vue.js,Fetch,Nuxtjs,我正在用Nuxt和无头Shopify建立一个网络商店。在全局组件(默认布局)中,我获取所有产品,因为它们需要全局可用: /layouts/default.vue async fetch() { await this.$store.dispatch('shop/products/setProducts'); }, async fetch() { await this.$store.dispatch('shop/products/setCurrentProduct',

我正在用Nuxt和无头Shopify建立一个网络商店。在全局组件(默认布局)中,我获取所有产品,因为它们需要全局可用:

/layouts/default.vue

  async fetch() {
    await this.$store.dispatch('shop/products/setProducts');
  },
  async fetch() {
    await this.$store.dispatch('shop/products/setCurrentProduct', this.slug).then(() => {
         ....
    });
  },
/store/products.js

export cost actions = {
  async setProducts(state) {
    const allProducts = await this.$axios.$get('/products');
    state.commit('setProducts', allProducts);
  },
}
export cost actions = {
    // null or empty
    const allProducts = await state.getters.allProducts;
    const result = allProducts.find(x => {
      return slug === x.slug.toString();
    });
    state.commit('setCurrentProduct', result);
}
现在,对于ProductDetailComponent,我使用
find
通过slug获得特定的产品:

/components/product detail.vue

  async fetch() {
    await this.$store.dispatch('shop/products/setProducts');
  },
  async fetch() {
    await this.$store.dispatch('shop/products/setCurrentProduct', this.slug).then(() => {
         ....
    });
  },
/store/products.js

export cost actions = {
  async setProducts(state) {
    const allProducts = await this.$axios.$get('/products');
    state.commit('setProducts', allProducts);
  },
}
export cost actions = {
    // null or empty
    const allProducts = await state.getters.allProducts;
    const result = allProducts.find(x => {
      return slug === x.slug.toString();
    });
    state.commit('setCurrentProduct', result);
}

现在的问题是,setCurrentProduct操作在加载所有产品之前触发。当然,我可以在ProductDetail组件中使用setProducts,但我希望避免多次调用该操作,正如我所说的,我需要全局范围内的所有产品。是否有一种方法仅在产品加载完成时触发setCurrentProduct操作?

您的默认布局组件在开始呈现产品详细信息之前不会等待$fetch调用完成

要解决此问题,可以在产品详细信息中使用
$fetchState.pending
属性(如中所示),也可以在商店中使用
nuxtServerInit
。此方法在服务器上调用一次,在呈现任何组件之前,您可以使用该方法用所有产品数据填充存储。请记住,如果您正在获取大量数据,这将影响应用程序的初始加载时间


我使用nuxt运行一个web应用商店,我使用nuxtInitServer方法获取所有基本的产品信息(标题、摘要、价格和slug),除了产品详细信息页面之外,我使用这些信息来支持所有内容。在产品详细信息中,我使用asyncData和商店中的产品id来获取更多关于该产品的详细信息。

hey here。谢谢你的评论!我应该提到,我正在SPA模式下使用该应用程序,因此我将无法使用nuxtServerInit。但我将看一看$fetchstate.pending方法。