【问题标题】:Vue.js: The view doesn't update after data is updated?Vue.js:数据更新后视图不更新?
【发布时间】:2017-11-11 06:24:20
【问题描述】:
<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>

视图不更新。此外,每当我尝试通过控制台访问响应/新闻对象时,我都会收到“参考错误:未定义的响应/新闻”。 AJAX 调用完美运行。

【问题讨论】:

    标签: javascript ajax mvvm vue.js axios


    【解决方案1】:

    您可以尝试使用箭头功能,例如:

    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) => {
            })

    【讨论】:

      【解决方案2】:
          <div v-for="CurNews in news">
              <div id="title">
              <h1>{{CurNews.title}}</h1>
          </div>
      

      id 是唯一的,你可以使用 class. data 属性应该是一个函数。

      data(): {
       news: [{
        title:"ABC", description: "VXAEW"
        }]
      }
      

      【讨论】:

      • 这不是问题... data 必须是 vue 组件实例的函数
      【解决方案3】:

      在您的 axios 请求中 .then 成功回调 this 没有指向 vue 实例,因为您使用的是普通函数语法,请改用胖箭头 =&gt; 函数语法,如下所示:

      mounted(){
          axios.get("your URL").then((response) => {
          this.news = response.data.articles;
          console.log(response.data.articles);
          }).catch(function(error){
          console.log(error);
          })
      } 
      

      或者在你挂载的块的开头声明一个 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);
          })
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-17
        • 2017-02-09
        • 2022-01-18
        • 2019-05-12
        • 2020-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多