can't access vue resource inside action vuex

Filipe Costa picture Filipe Costa · Aug 11, 2017 · Viewed 8.8k times · Source

hey guys i am trying to do a request inside my action on the vuex side, and i get this error:

Cannot read property '$http' of undefined

i set my vue-resource this way inside my main.js file:

import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import App from './App.vue'
import {routes} from './routes';
import {store} from './store/store';
import VModal from 'vue-js-modal'

Vue.use(VModal)
Vue.use(VueResource);
Vue.use(VueRouter);

const router = new VueRouter({
  routes
});

new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

then on the store:

addStyle(state,newStyleObj) {
    console.log(newStyleObj);
    var vm = this;
    this.$http.post('http://localhost:16339/api/Styles/PostStyle/', newStyleObj)
        .then(response => {
            state.tableStyles = response.body;
            console.log(state.tableStyles)
            console.log(response.body)
        }, error => {
            console.log(error);
        });
}

any help?

Answer

Fernando Saldaña picture Fernando Saldaña · Jan 14, 2019
import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

const axiosInstance = axios.create({
    baseURL: '',
    withCredentials: true,
})

Vue.prototype.$axios = axiosInstance
Vuex.Store.prototype.$axios = axiosInstance

This works for me.

Now you can access via this.$axios in Vue and Vuex.