Nuxt页面HTML在数据之前加载 [英] Nuxt page HTML is loaded before data

查看:26
本文介绍了Nuxt页面HTML在数据之前加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载产品详细信息的动态页面,但html在数据之前加载。

因此,当我尝试使用静电元素(如图像)时,会收到错误消息,指出该对象不存在。

为解决此问题,我给出了每个动态元素v-if="product != undefined",这些元素确实有效,但似乎不是解决此问题的好方法。

我像这样通过商店初始化我的数据

在我的页面中,我这样做:

async mounted() {
  await this.fetchProducts()
},
computed: {
  product() {
    return this.$store.state.products.producten.filter(product => product.id == this.$route.params.id)[0]
  }
}

然后在我的商店:

export const state = () => ({
  producten: []
})

export const mutations = {
  setProducts(state, data) {
    state.producten = data
  }
}

export const actions = {
  async fetchProducts({ commit }) {
    await axios.get('/api/products')
      .then(res => {
        var data = res.data
        commit('setProducts', data)
      })
      .catch(err => console.log(err));
  }
}

我尝试将mounted()替换为: beforeMount()created()fetch() 但似乎都不管用。

我还尝试了:

fetch() {return this.$store.dispatch('fetchProducts')}
Loader(v-if="$fetchState.pending")
Error(v-if="$fetchState.pending")
.product(v-else)
  // Product details...

推荐答案

您可以使用fetch hook调度fetchProducts

<script>
export default {
  fetch() {
    return this.$store.dispatch('fetchProducts')
  }
}
</script>

在模板中,使用$fetchState.pending标志防止在准备就绪之前呈现数据元素:

<template>
  <div>
    <Loader v-if="$fetchState.pending" />
    <Error v-else-if="$fetchState.error" />
    <Product v-else v-for="product in products" v-bind="product" />
  </div>
</template>

demo

这篇关于Nuxt页面HTML在数据之前加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆