【问题标题】:Vuex State Object Detection in Typescript VueTypescript Vue 中的 Vuex 状态对象检测
【发布时间】: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


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

【讨论】:

  • 是的,你需要这样做来代替 line.state.items[payload] += 1;
  • 我都试了。状态本身更新但不是我的组件@Riddhi
  • 使用控制台 this.$store.state.product 检查是否正在更新
  • 它已更新,但我的模板中的getAmountInCart 仍然显示0 而不是状态值
  • 这些变量是什么? this.$store.state.cart.items[bookId] && this.$store.state.cart.items[bookId].amount 安慰他们。我猜你正在更新一些其他变量
猜你喜欢
  • 2019-05-24
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2023-03-06
  • 2023-04-11
  • 2021-01-07
  • 2021-04-10
相关资源
最近更新 更多