我正在尝试创建简单的购物车系统,这是我的第一个VueJS练习。我从@vue/cli
开始使用Typescript和Vuex以及类style-component这个项目。现在,我停留在状态对象更改检测上。状态确实是更新的,但是我的组件没有重新渲染。
这是我的状态界面。很简单的。密钥是产品的ID
,Val是添加到购物车中的金额。
interface CartItem {
[key: string]: number;
}
这是我的模板
<template v-for="book in productLists.books">
<div class="cart-controller">
<button @click="addToCart(id)">-</button>
</div>
<div class="item-in-class">{{ getAmountInCart(book.id) }} In Cart</div>
</template>
我只有一个按钮用于将产品添加到购物车。添加之后,它应该使用添加到购物车中的商品数量来更新div.item-in-class
内容。
这是我的组成部分
<script lang="ts">
import { Vue, Component, Watch } from 'vue-property-decorator';
import { ACTION_TYPE as CART_ACTION_TYPE } from '@/store/modules/cart/actions';
import { ACTION_TYPE as PRODUCT_ACTION_TYPE } from '@/store/modules/product/actions';
@Component
export default class BooksLists extends Vue {
private cart = this.$store.state.cart;
@Watch('this.cart') // try to use watch here, but look like it doesn't work
oncartChange(newVal: any, oldVal: any){
console.log(oldVal);
}
private mounted() {
this.$store.dispatch(PRODUCT_ACTION_TYPE.FETCH_BOOKS);
}
private getAmountInCart(bookId: string): void {
return this.cart.items && this.cart.items[bookId] || 0;
}
private addToCart(bookId: number) {
this.$store.dispatch(CART_ACTION_TYPE.ADD_TO_CART, bookId);
console.log(this.cart);
}
}
</script>
更新1
我的动作也很简单。仅接收itemId并提交突变。
动作
const actions: ActionTree<CartState, RootState> = {
[ACTION_TYPE.ADD_TO_CART]({ commit }, item: CartItem): void {
commit(MUTATION_TYPE.ADD_ITEM_TO_CART, item);
},
};
突变
const mutations: MutationTree<CartState> = {
[MUTATION_TYPE.ADD_ITEM_TO_CART](state: CartState, payload: number): void {
if (state.items[payload]) {
state.items[payload] += 1;
return;
}
state.items[payload] = 1;
},
};
答案 0 :(得分:2)
为使更改具有响应性,您需要按以下步骤进行更新:
tempVar = state.items
tempVar['payload'] += 1;
state.items = Object.assign({}, tempVar)
或
Vue.$set(state.items,'payload',1)
Vue.$set(state.items,'payload',state.items['payload']+1)
有关更多详细信息,请参见https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats