javascript - Typescript Vue 中的 Vuex 状态对象检测

标签 javascript typescript vue.js vuex

我正在尝试创建简单的购物车系统作为我的第一个 VueJS 实践。我使用 Typescript 和 Vuex 以及类样式组件从 @vue/cli 开始这个项目。现在,我陷入了状态对象变化检测。状态确实更新了,但我的组件没有重新渲染。

这是我的状态界面。很简单。 Key 是产品的 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

我的 Action 也很简单。只接收 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;
    },
};

最佳答案

为了使更改具有反应性,您需要按如下方式更新它:

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://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

关于javascript - Typescript Vue 中的 Vuex 状态对象检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54533501/

相关文章:

javascript - 错误类型错误 : "this.posts is undefined" - in an angular type script class

typescript - Shaders with Typescript 和 React 三纤

javascript - 在 Vue js 中动态使用多个页面(组件)

php - 如何使用 Vuetables VUE.JS 在每一行添加 HREF 链接

javascript - JavaScript 中的正则表达式

javascript - 使用 lodash 根据条件向对象集合添加新属性

javascript - 延迟多次调用函数的最快方法

javascript - 普通数组与反引号数组生成的比较

javascript - vuex : $store. commit vs 直接调用函数

javascript - 从 Laravel 数据库中实时提取数据