我有一個加載產品詳細資訊的動態頁面,但 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...
uj5u.com熱心網友回復:
您可以使用fetch 鉤子來分派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>
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/381419.html
標籤:javascript Vue.js nuxt.js 哈巴狗 店铺
