一、安装
cnpm i vuex --save-dev
二、引入(main.js)
import store from './store'
new Vue({
el: '#app',
router,
store,//注册
components: { App },
template: '<App/>'
})
三、vuex配置 src > store > index.js(src下创建store目录,目录中创建index.js)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let state = {
box1: '0',
box2: '1'
}
let getters = {
getbox1(state){
return state.box1
},
getbox2(state){
return state.box2
}
}
let mutations = {
setBox1(state, str){
state.box1 += str
},
setBox2(state, str){
state.box2 += str
}
}
let actions = {
acBox1(context, str){
context.commit('setBox1', str)
},
acBox2(context, str){
context.commit('setBox2', str)
}
}
let store = new Vuex.Store({
state, getters, mutations, actions
})
export default store; // 导出配置项
四、组件中使用
this.$store.state.box1 // 获取state变量
this.$store.getters.getbox1 // 获取getter变量
this.$store.dispatch('acBox1', '1') // 调用actions的方法
this.$store.commit('setBox1', '1') // 调用mutations的方法
网友评论