programing

Axios 가로채기로 Vuex Store 가져오기

prostudy 2022. 4. 11. 21:27
반응형

Axios 가로채기로 Vuex Store 가져오기

이것의 주된 용도는 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-suries.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)
            }
        )
    })
}

참조URL: https://stackoverflow.com/questions/46948589/import-vuex-store-into-axios-interceptors

반응형