【发布时间】:2019-02-05 11:34:49
【问题描述】:
我正在尝试创建简单的购物车系统作为我的第一个 VueJS 实践。我从 @vue/cli 开始这个项目,使用 Typescript 和 Vuex 以及类样式组件。现在,我被困在状态对象变化检测上。状态确实更新了,但我的组件没有重新渲染。
这是我的状态界面。非常简单。键是产品的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 并提交到 Mutation。
动作
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;
},
};
【问题讨论】:
-
请添加变异代码ADD_TO_CART
-
@Riddhi 谢谢回复,我已经更新了请看一下
标签: javascript typescript vue.js vuex