VueX的应用

119 阅读1分钟

安装: npm install vuex@next --save 或者 yarn add vuex@next --save

一般结构:

Vuex中有一个createStore,可以创建一个新的store实例。
import { createStore } from 'vuex'
这个实例中可添加不同的moduleconst store = createStore({
    modules: {
        a: moduleA,
        b: moduleB,
    }
})

对于每个module,其内部结构为:
const module = {
    state: () => ({ sampleData: null}), // state初始化
    mutation: {SET_SAMPLE: (state, params)=>{state.sampleData = params}}, //更改状态的唯一方法
    actions: {函数调用commit执行mutation},
    getters: {sampleData: (state) => {return state.sampleData}}
}

最后在创建vue实例的时候加入store,基本结构搭建完成。

调用:

在各个页面都可以在computed下用mapGetters或者mapState使用相应的state。或者直接调用this.$store.state.module里面的state。

也可以this.$store.dispatch('path to the action', params)发送action请求通过mutation更改相应的state。