在store目录下创建index.js
import Vue from 'vue' import Vuex from 'vuex' const store = new Vuex.Store({ state: { user: null }, mutations: { setUser(state, data) { state.user = data; }, }, actions: { getUser({commit},token) { //这里调用接口 me({token: token}).then(data => { //提交到mutations更新状态 commit('setUser', data ); }).catch((data ) => { //错误处理 }); }, } }) export default store在main.js里引入store
import store from './store/index' ... new Vue({ el: '#app', store, template: '<App/>', components: {App} });触发action获取接口更新vuex
this.$store.dispatch('getUser')