【发布时间】:2018-05-04 16:15:27
【问题描述】:
尝试使用 Vue js 发送 http get 请求。看不出逻辑有任何问题,虽然使用 vuejs 没有太多经验。
不断收到这两个错误:
[Vue 警告]:挂载钩子错误:“TypeError:无法读取属性 'get' of undefined"
和
TypeError: 无法读取未定义的属性“get”。
var owm = new Vue({
el: '#owm',
data: {
debug: true,
weather: []
},
methods: {
loadWeather: function() {
this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade', function(data, status, request){
if(status == 200)
{
this.weather = data;
console.log(this.weather);
}
});
}
},
mounted: function () {
this.loadWeather();
}
});
使用vue资源更新了代码,错误消失了,但控制台不会记录任何数据,可能是什么问题?
Vue.use(VueResource);
var owm = new Vue({
el: '#owm',
data: {
weather: []
},
methods: {
loadWeather: function() {
this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]', function(data, status, request){
if(status == 200)
{
this.weather = data;
console.log(this.weather);
}
});
}
},
mounted: function () {
this.loadWeather();
}
});
编辑: 这段代码有效,但不是很理解 .then 函数,以及为什么请求不能与回调函数一起使用,但 .then 函数可以。
this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]').then((data) => {
this.weather = data;
console.log(this.weather);
【问题讨论】:
-
但不要使用
vue-resorce包。现在已弃用。阅读有关替代品的信息:medium.com/the-vue-point/retiring-vue-resource-871a82880af4 -
已安装 vue 资源并运行: var Vue = require('vue'); Vue.use(require('vue-resource'));在代码中,现在我收到错误消息“未定义要求”
标签: javascript http vue.js