将Vuex Store导入Axios拦截器

时间:2017-10-26 07:47:51

标签: javascript vuejs2 vuex

这主要用于存储一个新令牌,该令牌将在Vuex存储中自动刷新每个请求。 但是,我似乎并不了解如何导入商店,因此我可以从拦截器中存储.dispatch(' STORE_TOKEN')。

请注意,我的应用是SSR,而Vue APP本身是由工厂方法createApp()创建的。

如何导入商店并使其有效?

app.js

export function createApp () {
  // create store and router instances
  const store = createStore()
  const router = createRouter()

  // sync the router with the vuex store.
  // this registers `store.state.route`
  sync(store, router)

  // create the app instance.
  // here we inject the router, store and ssr context to all child components,
  // making them available everywhere as `this.$router` and `this.$store`.
  const app = new Vue({
    router,
    store,
    render: h => h(App)
  })

  // expose the app, the router and the store.
  // note we are not mounting the app here, since bootstrapping will be
  // different depending on whether we are in a browser or on the server.
  return { app, router, store }
}

Axios公司-instance.js

import axios from 'axios';

var instance = axios.create();

instance.defaults.baseURL = 'http://localhost:8000';
instance.interceptors.response.use((response) => {
    console.log("interceptop", response);

    console.log(this.$store);

    return response;
});

export default instance;

api.js

import axios from 'axios'
export function loginUser() {
    return new Promise((resolve, reject) => {
        axios({
            'method': 'post',
            'url': 'http://localhost:8000/auth/login',
            'data': {
                'email': 'user1@example.com',
                'password': '1234'
            }
        }).then((response) => {
            console.log(response);
            return response.data;
        }).then(
            (result) => {
                console.log("Response", result);
                resolve(result)
            },
            (error) => {
                reject(error)
            }
        )
    })
}

0 个答案:

没有答案