Vue2,Vuex-一站式在所有模块中使用Axios

时间:2019-03-06 10:04:08

标签: vue.js axios vuex vuex-modules

如何在一个地方的所有模块中提供 axios ?目前,我必须在所有模块中导入 axios ,所有模块都再次添加所有标头和令牌。如何避免这种情况? 目前,我将此文件作为 Vuex 的主文件(用户模块很大,但是重复了 axios 部分:

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import user from '@/store/modules/user'

Vue.use(Vuex)

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.defaults.baseURL = 'http://localhost:9999'

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}


export const store = new Vuex.Store({
    modules: {
        user
    },
    state: {
      token: localStorage.getItem('access_token') || null,
    },
    getters: {
        loggedIn(state){
            return state.token !== null
        }
    },
    mutations: {
        retrieveToken(state, token){
            state.token = token
        },
        destroyToken(state) {
            state.token = null
        }
    },
    actions: {

        retrieveToken(context, credentials){

            return new Promise((resolve, reject) => {
                axios.post('/api/auth/login', {
                  email: credentials.email,
                  password: credentials.password,
                })
                  .then(response => {
                    localStorage.setItem('access_token', response.data.access_token)
                    context.commit('retrieveToken', response.data.access_token)
                    resolve(response)
                  })
                  .catch(error => {
                    reject(error)
                  })
            })

        },

        destroyToken(context) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token

            if (context.getters.loggedIn) {

                return new Promise((resolve, reject) => {
                    axios.post('/api/auth/logout')
                        .then(response => {
                            localStorage.removeItem('access_token')
                            context.commit('destroyToken')
                            resolve(response)
                        })
                        .catch(error => {
                            localStorage.removeItem('access_token')
                            context.commit('destroyToken')
                            reject(error)
                        })
                })
            }
        }
    }
  })

0 个答案:

没有答案