1.新建user.js:
const user = {
state:{
user:""
},
mutations:{
USER_INFO(state,info){
state.user = info
}
},
actions:{
saveUserInfo({ commit },data){
commit('USER_INFO',data)
}
}
};
export default user
2.store/index.js引入:
import Vue from 'vue';
import Vuex from 'vuex';
import user from './user';
Vue.use(Vuex);
const store = new Vuex.Store({
modules:{
user
}
});
export default store
3.main.js引入store文件 :
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
...
//挂载
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
4.组件中login.vue中调用:
//this.$store.dispatch('saveUserInfo',response.data.data);//请求回来后,把用户信息存储到VUEX里
5.获取vuex中的数据
this.$store.state.user