我正在学习VueJs扩展我的知识,并且出于学习原因,我正在尝试使用axios库来获取JSON信息。 问题是在 HTML 中显示一个对象。在控制台中打印所有内容工作正常,除了 HTML。
当我加载一个页面时,它什么都不显示,而在控制台中它显示所有结果。
HTML 文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>VueJs</title>
</head>
<body>
<div class="innerBody" id="app">
<p style="width: 100%; height: 40px; background: gray;">{{getDescription}}</p>
</div>
<script src="app.js"></script>
</body>
</html>
JS文件:
new Vue({
el: '#app',
data:{
dataReceived: [],
errorReceived: [],
description: '',
},
methods: {
getJson: function(city){
axios.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+city+'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
.then(function (response) {
dataReceived = response;
console.log(dataReceived);
return dataReceived;
})
.catch(function (error) {
errorReceived = error;
console.log(errorReceived);
return errorReceived;
});
},
getDescription: function(){
description = dataReceived.data.query.results.channel.title;
console.log(description);
return description;
}
},
beforeMount(){
this.getJson('boston');
}
});
提前谢谢你。
最佳答案
您的代码有一些问题...
您的响应处理程序没有设置您的 Vue 实例的数据字段。例如,在下面的代码中。
dataReceived
不涉及dataReceived
你的 Vue 对象,这需要this.dataReceived
.axios.get('...') .then(function (response) { dataReceived = response; // <-- should be: this.dataReceived console.log(dataReceived); return dataReceived; })
您可以使用 ES2015 arrow-function绑定(bind)
this
到你的 Vue 实例,然后调用this.dataReceived = response
.axios.get('...') .then((response) => { this.dataReceived = response; console.log(dataReceived); })
您的模板尝试绑定(bind)
getDescription
对<div>
的文本内容的函数与{{getDescription}}
, 但正确的语法是{{getDescription()}}
(注意括号)。<div id="app">{{getDescription()}}</div>
但是,由于
getDescription
中使用的数据在 AJAX 响应返回之前不可用,绑定(bind)实际上应该是被新接收到的数据更新的东西。例如,此绑定(bind)可以是由 AJAX 响应处理程序设置的数据字段(例如,名为title
)。new Vue({ ... data() { return { dataReceived: {}, title: '' } }, methods: { getsJon() { axios.get('...') .then((response) => { this.dataReceived = response; this.title = parseTitle(this.dataReceived); }); }, parseTitle(data) { return /* ... */; } } }); // HTML <div id="app">{{title}}</div>
关于javascript - 尝试使用 VueJs 和 Axios 显示对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47045378/