vue2.x使用以下命令安装vuex
npm i vuex@3
store 使用模板
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
code:'',
},
//同步修改state里面的值
mutations: {
SET_CODE:(state, code)=>{
state.code = code;
},
},
//异步调用mutations里面的方法
//contxt.commit 利用上下文触发mutations某个方法
// vue代码里面 this.$store.dispatch触发action里面的定义的方法
actions: {
setCode(context,code){
context.commit('SET_CODE',code);
},
clearCode(context){
context.commit('SET_CODE','');
},
},
modules: {
}
})
在main.js函数里添加
import store from './store'
.....
.....
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
在模板里使用
this.$store.dispatch('setCode',code); //设置store里的值
this.$store.state.token;//获取store里的值