美文网首页
Vuex-mutation

Vuex-mutation

作者: 皇甫圣坤 | 来源:发表于2019-03-12 18:57 被阅读0次

mutation是唯一修改state值的入口
mutation是一个函数,使用方法类似于自定义事件
可以通过$store.commit方法触发

1. 创建

    {
      mutations: {
        mutation名字 (state,payload) {
          //修改操作state  payload就是commit时的第二个参数
        }
      }
    }

2. 在组件对应的事件函数里触发(提交)

    methods: {
      函数名 () {
        this.$store.commit('mutation名字',数据)//数据就是mutation函数中的第二个参数
      }
    }

3. 使用mutation 需要注意的地方

  1. mutation是同步的
  2. 将state中的属性写完整(操作的属性必须是state中已经存在的)
  3. 当我们设置的是对象时,我们应该使用下列方法

this.$set(对象,'属性','属性值')

vue.set(对象,'属性','属性值'
this.$delete(对象,'属性')
vue.delete(对象,'属性')
或者使用扩展运算符换成新的对象
this.obj = { 新的属性:值, ..this.obj}

4. eg

<div id="app">
  <button @click="changeMsgHanlder">按钮</button>
  {{$store.state.msg}}

</div>
<script src="./js/vue.js"></script>
<script src="./js/vuex.js"></script>
<script>
  const store = new Vuex.Store({
  state: {
    msg: '信息',
  },
  mutations: {
    changeMsg (state,msg){
      state.msg = msg
    }
  }
  })

  const app = new Vue({
    el: '#app',
    store,
    methods: {
      changeMsgHanlder () {
        this.$store.commit('changeMsg','传递过来的消息')
      }
    }
  })
</script>

相关文章

  • vuex-Mutation

    更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常...

  • Vuex-mutation

    mutation是唯一修改state值的入口mutation是一个函数,使用方法类似于自定义事件可以通过$stor...

  • vue状态管理模式vuex-Mutation

    更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。每个 mutation 都有一个字符串...

网友评论

      本文标题:Vuex-mutation

      本文链接:https://www.haomeiwen.com/subject/oktopqtx.html