无法使用 $http 或 Vue.http [英] Not able to use $http or Vue.http
问题描述
跟进
一组评论回答了这个问题.后续是 import/require 语句很重要的原因.我认为有效地做了同样的事情.
A combination of comments answered this question. A followup is why the import/require statements matter. I thought the effectively did the same thing.
原始问题我正在尝试使用 vue-resource
对 API 进行 REST 调用.到目前为止,我有一个工作 Vue 应用程序,它也使用 vue-material
并且运行良好.我只是无法获得对 http对象"的引用,我可以通过它进行 get/post/put 调用.
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.
堆栈基本上是 vue-cli
来创建 webpack/npm 项目.vue-resource
肯定在 package.json
中:
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
看起来像这样:
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);
我放置了那些 console.log
语句,因为我最初收到类似
I put those console.log
statements because I was initially getting errors like
cannot read property 'post' of undefined vue resource
果然,两个日志语句都产生未定义".Vue.http
产生相同的结果.
Sure enough, both log statements yield "undefined". Vue.http
yields the same.
我在这里做错了什么?有趣的是,vue-material
运行良好...
What am I doing wrong here? Interestingly, vue-material
is working fine...
更新
检查 Vue 实例内部仍然产生 undefined:
Checking inside the Vue instance still yields undefined:
mounted: () => {
console.log(this.$http);
}
更新 2 -- 一个有效的解决方案
感谢您的评论,他们的组合解决了这个问题.首先将require
改成导入:
Thanks for the comments, a combination of them solved it. Firstly change the require
to import:
import VueResource from 'vue-resource';
Vue.use(VueResource);
并使用旧的方式为mounted
创建一个函数:
And use the old way of creating a function for mounted
:
mounted: function () {
console.log(this.$http);
}
推荐答案
您需要从 Vue 实例方法中检查 this.$http
:
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);
}
})
这篇关于无法使用 $http 或 Vue.http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!