怎么修改vuex里面的数据

152 阅读1分钟

Vuex 使用 mutations 来修改状态数据。Mutation 提供了一种在同步方式下修改 Vuex state 的方式,确保所有状态的变更都可以被追踪。

首先,在 Vuex store 中定义一个 mutation。可以通过 store.commit() 方法来触发 mutation。

例如:我们给state中的cart追赠数据

store/index.js

state:{
  cart:[]
},
mutations:{
  updateCart(state,cart){
      state.cart=cart
    }
}

渲染数据:

<view  v-for="(item,index)in cart" :key="index">
   xxx
<view>

import { mapState } from 'vuex';
  export default {
    computed:{
      ...mapState(['cart'])
    }
  }

需求:增加新的数据(方法)

错误示范:

案例1:

this.$store.state.cart.push()

问题:很明显这么干是错误的,因为state的数据只能由mutations来修改

案例2:

const cartList=this.$store.state.cart
cartList.push()
this.$store.commit('updateCart',xxxx)

问题:这样也是错误的,看起来是通过commit触发mutations来修改cart数据的,其实

const cartList=this.$store.state.cart
cartList.push() 

这两步就已经可以实现数据的添加,虽然数据添加成功了,但是在控制台vuex中cart的数据并没有发生变化,这是因为state中的数据虽然更改了,但是没有经过mutations,所有状态的变更都不可以被追踪到。

手动点击Root相当于刷新vuex,这时候vuex中的cart数据更新到最新的状态,但是并不知道什么时候更改的,对后期如果想要操作cart中的数据有影响

正确写法:

深拷贝,在新增

computed:{
   cart(){
        return JSON.parse(JSON.stringify(this.$store.state.cart))
   }

     
method:{
  updateData(){
      this.cart.push(xxx)
      this.$store.commit('updateCart',this.cart)
}