3

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?

Filipe Costa
  • 545
  • 3
  • 12
  • 32

6 Answers6

11
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.

Felipe Augusto
  • 7,733
  • 10
  • 39
  • 73
6

You can access Vue instance from the store using this._vm.

this._vm.$http.post()
NaN
  • 1,955
  • 13
  • 16
1

Here is a proper explanation of the problem that $http is not accessible within vuex https://stackoverflow.com/a/42571288/6355502

The state can only be altered in mutations. NOT in actions. Just commit a mutation from inside of the action to alter the state.

I tried the same last night and got error messages that forced me to do the async fetching in actions which trigger mutations. You cannot do async operations in mutations and you cannot alter the state in actions, so you have to split the code.

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

// in mutations
setTableStyles(state, payload){
state.tableStyles = payload; // or state.tableStyles.push(...payload) if tableStyles is an Array 
}
Reiner
  • 1,621
  • 1
  • 16
  • 22
1

Outside vue instance (store in this case) use Vue.http (without the dollar sign), inside instance use this.$http.

You can find more on github.

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
gardan
  • 11
  • 2
  • Or this._vm.$http.get... in any vuex action which avoids having to import the Vue instance in every time – D Durham Jul 30 '18 at 15:02
0

access to axios with Vue.prototype.$http

login({commit}, loginFormData) {
            return new Promise((resolve, reject) => {
                commit('auth_request');
                Vue.prototype.$http({url: '/user/login', data: loginFormData, method: 'POST'})
                    .then(resp => {
                        const token = resp.data.data.token;
                        const user = resp.data.data.profile;
                        localStorage.setItem('token', token);
                        localStorage.setItem('user', JSON.stringify(user));
                        Vue.prototype.$http.defaults.headers['Authorization'] = 'Bearer ' + token;
                        this.state.user = JSON.parse(localStorage.getItem('user')) || '';
                        this.state.token = localStorage.getItem('token') || '';
                        commit('auth_success', {token, user});
                        resolve(resp)
                    })
                    .catch(err => {
                        commit('auth_error');
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        reject(err)
                    })
            })
        },
mohammad nazari
  • 951
  • 8
  • 11
0

Try Accessing vue Properties by this way this._vm.$yourDesiredPropertyName For example this._vm.$http etc It worked for me . You can access all the properties which are properly registered to vue instance