dcranmer's avatar

Vue-resource: cannot read property '$http' of undefined

'this' is a part of Vue.js that I can't seem to get straight. I've got a component that allows me to delete list items. But no matter how I try to call a vue-resource $http method, it gives me an uncaught TypeError: cannot read property '$http' of undefined.

My main.js file is being built via Laravel Elixir-Vueify. I am pulling in vue-resource, which is located in /resources/assets/js into main.js like this:

import Vue from 'Vue';
import Alert from './components/Alert.vue';
import Partners from './components/Partners.vue';

Vue.use(require('./vue-resource.min.js'));

In my Partners component, I have a delete method:

    methods: {

      deletePartner (index, partner) {
        // delete from database via ajax
       this.vm.$http.delete('/partners/' + partner.id)
            // then remove item from list in view
            .then(self.list.$remove(index))
            .catch(this.onError.bind(this));
      }

This is what used to work before I was using Vuify (see the Laracast lesson on asynchronous forms). I've tried called $http as 'this.$http', and the same thing happens. I know that I don't fully understand what governs the usage of 'this' or 'this.vm'. But what is the correct way to call an $http method? Or am I pulling vue-resource in incorrectly?

0 likes
5 replies
joshbodine@gmail.com's avatar

I am having a similar problem and not sure how to resolve.

I have a custom component that I call within my App.vue file for listing my customer accounts. Then, in the custom component (Accounts.vue) I import Accounts.js that has an accounts object with a static method for calling the my API and getting a list of accounts. When I use "this.$http" in my Accounts.vue component it works fine, but if I use in my Account.js object, it is undefined. I realize that is due to the scope of "this" being my Account object, but I am trying to determine how to get access to the Vue this.$http object where my API is defined? Any help on how to do so would be appreciated.

main.js

import Vue from 'vue'
import axios from 'axios'

Vue.prototype.$http = axios

Accounts.vue

import Account from '../../../entities/Account'
export default {
  data () {
    return {
      Accounts: []
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      Account.all(data => {
        this.Accounts = data
      })
    }
  }
}

Account.js

class Account {
  static all (then) {
    return this.$http.get('Organizations/Accounts')
      .then(response => then(response.data.items))
      .catch()
  }
}

export default Account
jamesbrown2's avatar

joshbodine, I had similar problem. Try something like:

import Vue from 'vue'

class Account {
  static all (then) {
    return Vue.prototype.$http.get('Organizations/Accounts')
      .then(response => then(response.data.items))
      .catch()
  }
}

export default Account

Please or to participate in this conversation.