vuex(状态机)
index.js
import service from '../service.js';
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
/**
* 是否需要强制登录
*/
forcedLogin: true,
hasLogin: false,
userName: "",
msg: {}
},
mutations: {
login(state, userName) {
state.userName = userName || '新用户';
state.hasLogin = true;
},
logout(state) {
state.userName = "";
state.hasLogin = false;
service.removeUser();
},
setmsg(state, msg) {
state.msg = msg
}
}
})
export default store
———————————————————————————————————————————————————————————————
引入:import {
mapState,
mapMutations
} from 'vuex'
设置值:
methods: {
...mapMutations(['login', 'setmsg']),
}
let userMsg = {
user_grade: data.data.user_grade,
discount_rate: data.data.discount_rate
}
that.setmsg(userMsg);
获取值:
computed:{
...mapState(['forcedLogin', 'hasLogin', 'userName','msg']),
}
this.msg(就可以出来了)