Not able to use $http or Vue.http

落花浮王杯 提交于 2019-12-12 18:12:16

问题


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>


来源:https://stackoverflow.com/questions/43666618/not-able-to-use-http-or-vue-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!