vuex(篇2)——Mutations

组件中直接修改vuex中的数据——这个行为是禁止的

Vuex 是一个专为 Vue.js应用程序开发的状态管理插件。它采用集中式存储管理应用的所有组件的状态,而更改状态的唯一方法是提交mutation

vuex中修改vuex中的数据(无传参)

mutations定义的函数会有一个默认参数state,这个就是存储在Store中的state对象。

在vuex中定义函数

 mutations: {
        add(state){
            state.count++
        }
    }

组件中调用vuex中的mutation函数

方式1:在组件中,通过this.$store.commit(方法名)完成触发

<button @click="add">点击添加</button>
methods:{
      add() {
          this.$store.commit("add")
      }
    }

方式2:在组件中导入mapMutations函数

导入的mapMutations函数,将需要的mutations函数映射为当前组件的methods方法

<button @click="addCount">点击</button>
import {mapMutations} from 'vuex'
    methods:{
        ...mapMutations(['add']),
        addCount() {
            this.add()
        }
    }

vuex中修改vuex中的数据(传参)

在vuex中定义函数

mutations: {
        add(state){
            state.count++
        },
        addN(state,payload){
            this.state.count+=payload.number
        }
    }

如果仅有一个参数时,那payload对应的就是这个参数值
如果是多参数的话,那就会以对象的形式传递,此时的payload是一个对象,可以从对象中取出相关的数据。

组件中触发vuex中的函数

方式1 通过this.$store.commit(方法名)完成触发

<button @click="add">点击添加1</button>
<button @click="addN">点击添加3</button>
methods:{
      add() {
          this.$store.commit("add")
      },
      addN() {
          this.$store.commit('addN',{
              number: 3
          })
      }
    }

方式2:在组件中导入mapMutations函数

<button @click="addCount">点击</button>
<button @click="addCountN">点击N</button>
 methods:{
        ...mapMutations(['add','addN']),
        addCount() {
            this.add()
        },
        addCountN() {
            this.addN({number: 3})
        }
    }

在 Vuex 中,mutation 都是同步事务

猜你喜欢

转载自blog.csdn.net/weixin_40119412/article/details/107595225