H
H
haa2022-02-13 20:37:21
Vue.js
haa, 2022-02-13 20:37:21

How to properly connect axios for vuex?

I use nuxtjs/axios, created a plugin to work as indicated on the site

export default function ({ $axios }, inject) {

  const api = $axios.create({
    headers: {
      common: {
        'X-Requested-With': 'XMLHttpRequest',
        'Accept'          : 'application/json',
      }
    }
  })

  api.setBaseURL('http://laravel/api/')

  inject('api', api)
}


I connect the plugin
plugins: [
    '@/plugins/axios',
  ],


through the beforeRouteEnter hook, I call the action load_article
async beforeRouteEnter(to, from, next) {

    await store.dispatch('article/load_article', {
      id: to.params.id
    })

  }

when called, I get Uncaught (in promise) TypeError: _this.$api is undefined. The fact that undefined is understandable!
export const FETCH_ARTICLE = 'load_article'

export default {
  async [FETCH_ARTICLE]({ commit }, payload) {

    let endpoint = 'article/'+payload.id
    const data = ( await this.$api.get(endpoint) ).data

    commit(SET_ARTICLE, {
      data: data.data
    })
  },
}

The question is how to connect axios in this case? I used $axios.$get, I get undefined

Connected without a plugin, through nuxt.config.js file
axios: {
    baseURL: 'http://laravel/api/',
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Glebov, 2022-02-14
@haa

Axios needs to be added to nuxt.config.js as a module
https://axios.nuxtjs.org/setup#configure
Instead of beforeRouteEnter use fetch hook
https://nuxtjs.org/docs/features/data-fetching/
or nuxtServerInit if you need to call method on all pages
https://nuxtjs.org/docs/directory-structure/store/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question