我正在与NuxtJS和VueJS合作。在状态发生变化后,组件无法重新渲染时出现问题。
index.js文件
Vue.use(Vuex)
const state = {
productsHome: [],
accessToken: {},
collections: {},
product: {},
cart: {},
}
const getters = {
productForHomepage (state) {
return state.productsHome
},
productForPdp (state) {
return state.product
},
cart (state){
return state.cart
}
}
const actions = {
nuxtServerInit (context) {
//good place to set language
},
GET_HOME(){
api.getHomepageProducts().then(response => {
this.commit('setHomeProducts', response.data)
})
},
GET_PDP(sth){
api.findBySlug(this.app.router.history.current.params.slug).then(response => {
this.commit('setPDPData', response.data)
})
},
ADD_TO_CART(store, id){
api.addToCart(id).then(res => {
store.commit('updateCart', res.data)
})
}
}
const mutations = {
setHomeProducts(state, data){
state.productsHome = data
},
setPDPData(state, data){
state.product = data[0]
},
updateCart(state, data){
for (var optbox of data) {
state.cart[optbox.id] = optbox;
}
// state.cart.set('iteams', 'count', 1)
}
}
const createStore = () => {
return new Vuex.Store({
state,
getters,
mutations,
actions
});
}
export default createStore;
这是组件
<template>
<div>
<div class="content">
<p>
This is cart
</p>
{{ cart }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
cart: this.$store.state.cart
}
},
watch: {
cart: function(val){
cart = this.$store.state.cart
}
},
methods: {
updateCart: function(){
console.log(this)
}
}
}
</script>
答案 0 :(得分:1)
执行此操作时:
computed: {
cart(){
return this.$store.state.cart
}
}
您使用购物车状态的值初始化数据,但是当购物车状态发生变化时,它不会保持更改,这是一次性交易,您可以在this JSFiddle中看到< / p>
您实际想要做的是使用计算:
{{1}}
现在,只要商店中的购物车状态发生变化,组件中购物车的价值也会发生变化。
这就是JSFiddle:https://jsfiddle.net/craig_h_411/zrbk5x6q/