2 回答
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個贊
products不要放在data里定義,應(yīng)該放在computed計(jì)算屬性里定義:
<script>
export default {
name: "index",
computed: {
poducts() {
return this.$store.state.app.products
}
},
mounted() {
if (this.products.length <= 0) this.$store.dispatch('getProducts');
}
}</script>錯誤原因:
你先給data中的products賦值為this.$store.state.app.products然后vuex異步獲取數(shù)據(jù)給state.app.products。
此時vuex中的products得到數(shù)據(jù)后更新,但是data不會響應(yīng)式的根據(jù)vuex中的products的改變來改變,所以data里的products沒有數(shù)據(jù)。
切換路由后,你這個組件沒有進(jìn)行緩存,它在切換其他路由時已經(jīng)被銷毀,切換回來時重新渲染,取得vuex中的products。
此時vuex中products已經(jīng)有了值,所以data里的products能得到數(shù)據(jù)。
下面是vuex文檔中有提到得到state里值的方式最好是寫在計(jì)算屬性里面
vuex文檔
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個贊
沒看懂你問題 你是在組件中獲取不到store中更新后的products數(shù)據(jù)還是組件更新后 store獲取不到products數(shù)據(jù)
一般都是利用監(jiān)聽來監(jiān)聽store中數(shù)據(jù)變化 希望對你有幫助 下次問題在描述具體點(diǎn)
`<script>
export default {
name: "index",
data() {
return {
products: this.$store.state.app.products//這里你賦值給products 模板循環(huán)的是 productData
}
},
mounted() {
//這里是每次進(jìn)入這個組件都會執(zhí)行這里的代碼
//你在這里從新賦值給store中g(shù)etProducts你不需要參數(shù)嗎
if (this.products.length <= 0)
this.$store.dispatch('getProducts');
}
}</script>`
添加回答
舉報(bào)
