vuex的基本使用(state和mutations)

66 阅读1分钟

一. 什么是store

store相当于是一个仓库,里面存放了state、mutations、getters、actions

二. state

在相应的Vue中使用。如在template中使用则用$store.state.xxx去获取 在script标签中用 this.$store.state.xxx

三. mutations

如果要更改state的话,必须要通过mutations去做更改。如果通过直接修改state,会导致不清楚是哪部分改变了仓库数据。 如何使用?

在store下的index.js中定位mutations写主要逻辑,也就是需要定义的方法

mutations:{
    increment(state,param){
        state.count+=param;
    }
}

在需要执行此方法的Vue文件中 进行点击事件,定义点击事件 this.$store.commit('increment',param)

methods:{
    addCount(param){
        this.$store.commit('increment',param);
    }
}