vuex之mutation示例说明

mutation中文意思是改变、变异
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
Vuex 中的 mutation 非常类似于事件:
”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

<div id="app">
    {{count}}
    <button @click="add">+ 1</button>
</div>
const store=new Vuex.Store({
    state:{//所有的状态,单例模式处理
        count:10.123,
    },
    getters:{//是相当于store的计算属性
        /*aa:(state)=>{
            return state.count.toFixed(2);
        }*/
        aa(){
            return store.state.count.toFixed(2);
        }
    },
    mutations:{//相当于事件
        increment(state,data){
            state.count+=data.addData;
        }
    }
})

const vm=new Vue({
    el:'#app',
    store,//将store挂载到vue实例上
    computed:{
        count(){
            return this.$store.getters.aa;//通过computed的计算属性获取store中getters中对应的值
        }
    },
    methods:{
        add(){
            console.log(this.$store.state.count)
            //this.$store.commit("increment",Math.random());//处理store的mutation中对应的事件,可以改变state状态,可以传入参数
            //对象风格提交
            this.$store.commit({
                type:"increment",
                "addData":Math.random()
            });
        }
    },
    components:{},
})
//在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
    /*mutations: {
        increment (state, payload) {
            state.count += payload.amount
        }
    }*/

    /*store.commit('increment', {
        amount: 10
    })*/

//对象风格的提交方式

    /*mutations: {
        increment (state, payload) {
            state.count += payload.amount
        }
    }  */

    /*store.commit({//与上边的例子只是写法不同
        type:'increment',
        amount: 10
    })*/

//Mutation 需遵守 Vue 的响应规则
//Mutation 必须是同步函数(因为 任何在回调函数中进行的状态的改变都是不可追踪的)


//mapMutations映射使用
methods:{
  ...mapMutations(['Mutation1','Mutation2']),
  otherMethods(){
    //xxx
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 3,022评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,223评论 0 6
  • Vuex 是什么? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有...
    skycolor阅读 926评论 0 1
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 4,767评论 7 61
  • 01 去年的10月1号,毛晓彤发了一条微博,内容写道,“从没想象过这一幕会出现在我眼前。” 结果评论区引来了许多陈...
    夕夕酱阅读 989评论 1 2

友情链接更多精彩内容