我有一个加载产品详细信息的动态页面,但 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()
替换为:
在Mount()之前
,
创建(),
获取()
但似乎都不起作用。
我也尝试过:
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>
关于javascript - Nuxt页面HTML在数据之前加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70350195/