[英]Vue.js: The view doesn't update after data is updated?
<div id="app">
<h1> News Aggregator </h1>
<div v-for="CurNews in news">
<div id="title">
<h1>{{CurNews.title}}</h1>
</div>
<div id="description">
<p>{{CurNews.description}}</p>
</div>
</div>
</div>
<script>
const API_KEY = "XXXXXXXXXX";
const url = "https://newsapi.org/v1/articles?";
const app = new Vue({
el: '#app',
data:{
news: [{
title:"ABC", description: "VXAEW"
}]
},
mounted(){
axios.get("https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=XXXXXXXXXXX").then(function(response){
this.news = response.data.articles;
//app.$set(this.news, response.data.articles);
console.log(response.data.articles);
}).catch(function(error){
console.log(error);
})
}
});
</script>
The view does not update. 该视图不会更新。 Also, whenever I try to access the response/news object through the console, I get "Reference Error: response/news in not defined". 另外,每当我尝试通过控制台访问response / news对象时,都会收到“参考错误:respond / news in not defined”。 The AJAX call works perfectly. AJAX调用工作完美。
In your axios request .then
sucess callback this
is not pointing to the vue instance since you are using a normal function syntax, use fat arrow =>
function syntax instead like this: 在axios请求中.then
成功回调,因为您使用的是普通函数语法,所以this
并不指向vue实例,请改为使用fat arrow =>
function语法,如下所示:
mounted(){
axios.get("your URL").then((response) => {
this.news = response.data.articles;
console.log(response.data.articles);
}).catch(function(error){
console.log(error);
})
}
Or else declare a var vm
at the start of your mounted block pointing the vue instance like this: 否则在挂载的块的开头声明一个var vm
,指向vue实例,如下所示:
mounted(){
var vm = this;
axios.get("your URL").then(function(response) {
vm.news = response.data.articles;
console.log(response.data.articles);
}).catch(function(error){
console.log(error);
})
}
<div v-for="CurNews in news">
<div id="title">
<h1>{{CurNews.title}}</h1>
</div>
id is unique, you can use class. id是唯一的,可以使用class。 The data attribute should be a function. 数据属性应该是一个函数。
data(): {
news: [{
title:"ABC", description: "VXAEW"
}]
}
You can try using arrow function like: 您可以尝试使用箭头功能,例如:
fetch("/static/data/data_table.json", { method: "GET", headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } } ) .then((response) => { return response.json() }).then ((json) => { this.resultJson = json }).catch( (ex) => { })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.