Can't get state stored by Vuex in ~/plugins/axios.js

时间秒杀一切 提交于 2019-12-24 17:16:12

问题


I have problem to get token stored by Vuex in ~/plugins/axios.js. Hope your guys take a look for me please.

My Vuex: ~/store/index.js

export const state = () => ({
  authUser: null,
  token: null
})

export const mutations = {
  SET_USER: function (state, user) {
    state.authUser = user
  },
  SET_TOKEN: function (state, token) {
    state.token = token
    instance.defaults.headers = { Authorization: 'Bearer ' + token }
  }
}

export const actions = {
  async nuxtServerInit ({ commit }, { req }) {
    ...
  },
  async login ({ commit }, { username, password }) {
    ...
  }
}

const store = () => new Vuex.Store({
  state,
  mutations,
  actions,
  modules: {
    feed,
    users,
    notification,
    messenger
  }
})

export default store

const VuexStore = () => {
  return store
}
export { VuexStore }

~/plugins/axios, which VuexStore.state is not data!

import axios from 'axios'
import {VuexStore} from '~/store'

var api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/'
})
console.log(VuexStore.state.token) // Null data

export default api

Console log is:

ƒ VuexStore() {
  return store;
}

回答1:


Not tested but you could use something like:

~/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = () => ({
  authUser: null,
  token: null
})

const mutations = {
  SET_USER: function (state, user) {
    state.authUser = user
  },
  SET_TOKEN: function (state, token) {
    state.token = token
    instance.defaults.headers = { Authorization: 'Bearer ' + token }
  }
}

const getters = {
 ...
}

const actions = {
  async nuxtServerInit ({ commit }, { req }) {
    ...
  },
  async login ({ commit }, { username, password }) {
    ...
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  getters,
  modules: {
    ...
  }
});

~/plugins/axios.js

import axios from 'axios'
import VuexStore from '~/store'

var api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/'
})
console.log(VuexStore.state.token) 

export default api


来源:https://stackoverflow.com/questions/48658369/cant-get-state-stored-by-vuex-in-plugins-axios-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!