install

‘cnpm install vuex –save’

store.js
export let state = {
    count: 1
}

export let mutations = {
    increment(state) {
        // 变更状态
        state.count++
    },
    add(state, n) {
        state.count += n
    },
}

export let getters = {
    done(state) {
        return state.count + 5;
    },
}

export let actions = {
    increment(context) {
        context.commit('increment')
    },
    incrementAsync(context) {
        // 延时1秒  
        setTimeout(() => {
            context.commit('increment')
        }, 1000)
    }
}
main.js
import Vue from 'vue'
import Vuex from 'vuex'
import { state, mutations, getters, actions } from './store'

Vue.use(Vuex)

const store = new Vuex.Store({
    state,
    mutations,
    getters,
    actions
})

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
还可以分模块
const moduleA = {
    state: { ...
    },
    mutations: { ...
    },
    actions: { ...
    },
    getters: { ...
    }
}

const moduleB = {
    state: { ...
    },
    mutations: { ...
    },
    actions: { ...
    }
}

const store = new Vuex.Store({
    modules: {
        a: moduleA,
        b: moduleB
    }
})

//使用
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
Logo

前往低代码交流专区

更多推荐