一、安装及引用
npm install vuex --save
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.use(ElementUI)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
store
})
- 3.新建模块
新建一个用于管理环境变量的模块src/store/modules/env.js
const state = {
envVariable: 'branch'
}
const mutations = {
CHENGE_ENV: (state, env) => {
if (env) {
state.envVariable = env
}
}
}
const actions = {
envVariable ({commit, state}, env) {
commit('CHENGE_ENV', env)
}
}
export default {
state,
mutations,
actions
}
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import env from './modules/env'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
env
},
getters
})
export default store
const getters = {
envVariable: state => state.env.envVariable // 此处state.name , name与引入的模块名称相同
}
export default getters
this.$store.getters.envVariable
// 对应的是模块中actions 设置的提交方法
this.$store.dispatch('envVariable', val)