Aiv*_*ras 1 html javascript json vue.js axios
我正在扩展我学习 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>
Run Code Online (Sandbox Code Playgroud)
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');
}
});
Run Code Online (Sandbox Code Playgroud)
先感谢您。
您的代码有一些问题...
您的响应处理程序没有设置 Vue 实例的数据字段。例如,在下面的代码中。dataReceived不引用dataReceived您的 Vue 对象,这需要this.dataReceived.
axios.get('...')
.then(function (response) {
dataReceived = response; // <-- should be: this.dataReceived
console.log(dataReceived);
return dataReceived;
})
Run Code Online (Sandbox Code Playgroud)
您可以使用ES2015 箭头函数绑定this到您的 Vue 实例,然后调用this.dataReceived = response.
axios.get('...')
.then((response) => {
this.dataReceived = response;
console.log(dataReceived);
})
Run Code Online (Sandbox Code Playgroud)您的模板尝试将getDescription函数绑定到<div>with的文本内容{{getDescription}},但正确的语法是{{getDescription()}}(注意括号)。
<div id="app">{{getDescription()}}</div>
Run Code Online (Sandbox Code Playgroud)
但是,由于在getDescriptionAJAX 响应返回之前使用的数据不可用,因此绑定实际上应该是由新接收到的数据更新的内容。例如,此绑定可以title是由 AJAX 响应处理程序设置的数据字段(例如,named )。
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>
Run Code Online (Sandbox Code Playgroud)