Not able to use $http or Vue.http

Manish Patel picture Manish Patel · Apr 27, 2017 · Viewed 13.5k times · Source

FOLLOW UP

A combination of comments answered this question. A followup is why the import/require statements matter. I thought the effectively did the same thing.

ORIGINAL QUESTION I'm trying to use vue-resource to make REST calls to an API. I have up to now a working Vue app that also uses vue-material and it works nicely. I'm just having trouble getting a reference to the http "object" through which I can make get/post/put calls.

The stack is basically vue-cli to create a webpack/npm project. vue-resouce is definitely in package.json:

"vue": "^2.2.1",
"vue-resource": "^1.3.1"

main.js looks like this:

import Vue from 'vue';
Vue.use(require('vue-material'));
Vue.use(require('vue-resource'));

import App from './App.vue'

console.log(this.$http);

new Vue({
el: '#app',
//other stuff
});

console.log(this.$http);

I put those console.log statements because I was initially getting errors like

cannot read property 'post' of undefined vue resource

Sure enough, both log statements yield "undefined". Vue.http yields the same.

What am I doing wrong here? Interestingly, vue-material is working fine...

UPDATE

Checking inside the Vue instance still yields undefined:

mounted: () => {
    console.log(this.$http);
}

UPDATE 2 -- a solution that works

Thanks for the comments, a combination of them solved it. Firstly change the require to import:

import VueResource from 'vue-resource';
Vue.use(VueResource);

And use the old way of creating a function for mounted:

mounted: function () {
    console.log(this.$http);
}

Answer

thanksd picture thanksd · Apr 27, 2017

You need to check for this.$http from within a Vue instance method:

import Vue from 'vue';
Vue.use(require('vue-resource'));

new Vue({
  el: '#app',
  mounted: function() {
    console.log(this.$http);
  }
})