Not able to use $http or Vue.http

2019-07-27 07:11发布

问题:

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);
}

回答1:

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);
  }
})


回答2:

You can try an alternative. From the Vue web site: https://vuejs.org/v2/cookbook/adding-instance-properties.html#Real-World-Example-Replacing-Vue-Resource-with-Axios

"Alias axios to Vue.prototype.$http. Then you’ll be able to use methods like this.$http.get in any Vue instance"

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.2/axios.js"></script>
<script>
Vue.prototype.$http = axios

...
this.$http
      .get('https://jsonplaceholder.typicode.com/users')
      .then(function(response) {
        vm.users = response.data
      })
...
</script>