Axios is not defined

-1

I am implementing axios in my application in Laravel I had to do by hand the implementation of laravel mix among other things. Package.js

"devDependencies": {
    "axios": "^0.18.0",
    ..
  },

I already tried to include it in my app.js and it does not work for me

import axios from 'axios'
Vue.use(axios)

Someone knows why I keep marking error

[Vue warn]: Error in created hook: "ReferenceError: axios is not defined"

Component

axios.get('api/bloques')
            .then((res) => {
                console.log(res)
            })
            .catch((err) => {
                console.warn(err)
            })

I do not know if I need to add it somewhere to use it globally.

    
asked by DoubleM 11.12.2018 в 00:53
source

2 answers

0

Try to include it in your file, componente.js, that is:

import axios from 'axios'
axios.get('api/bloques')
            .then((res) => {
                console.log(res)
            })
            .catch((err) => {
                console.warn(err)
            })
    
answered by 11.12.2018 в 01:00
0

I recommend you to create a basic service to help you in all tasks with axios, such that:

// axios-base.js

import axios from 'axios'

const VueAxios = axios.create({
  // timeout: 10000,
  headers: {'X-AUTH-TOKEN': authToken}
})

const AxiosUtils = {
  vuex: null,
  errorNotifier: null
}

export default {
  getApiResource (url, params, options = {}) {
    return VueAxios.get(Routing.generate(url, params), options)
    // El Routing.generate(...) es un script de Symfony para utilizar su generador de rutas, tu puedes pasárle la url a cada uno de los métodos como quieras (la recibe como primer parámetro en .get, .post, ... etc)
  },
  postApiResource (url, params, body) {
    return VueAxios.post(...)
  },
  patchApiResource (url, params, body) {
    return VueAxios.patch...
  },
  deleteApiResource (url, params, body) {
   ...
  },
  setErrorNotifier (notifier) {
    AxiosUtils.errorNotifier = notifier
  }
}

Once done this you import into App.vue (or your main file):

import Api from 'turuta/axios-base.js'

If you do it like this you will have it much more controlled, centralized and you can control any exception and / or interceptors from here.

If you still do not think twice, try removing it from --save-dev and save it only with --save.

    
answered by 12.12.2018 в 13:53