繁体   English   中英

在Vue中获得Ajax响应后如何更改/触发HTML DOM

[英]How to change/trigger HTML DOM after getting ajax response in Vue

我是Vue的新手。 我在努力并尝试了最后半天没有任何解决方案。 在这里,我需要根据ajax响应自动更改待办事项文本。 使用setInterval需要更新vue实例并更改HTML DOM。 更新待办事项时,无法自动更改DOM

<div id="app">
      <ul>
        <li v-for="question in todos.text">
          {{ question.text }}
        </li>
      </ul>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: function () {
            return { 
                message: 'You loaded this page on ' + new Date().toLocaleString(),
               todos: 
                  { 
                    Event: 'Event1',
                    text: [
                      { text: 'Learn JavaScript1' },
                      { text: 'Learn Vue1' },
                      { text: 'Build something awesome1' }
                    ] 
                }
            }           
        },
        mounted: function() {
            setInterval(function () {
                axios({
                  method: 'post',
                  url: 'test.php',
                  data: {
                    firstName: 'Fred',
                    lastName: 'Flintstone'
                  }
                }).then(response => {
                    console.log(response.data);
                    this.todos = response.data;
                    Vue.set(this, todos, response.data ); 
                  })
                  .catch(err => {
                    console.log(err);
                  });
            }, 5000);
        }
    })
</script>

范围this势必窗口,而不是你的Vue的实例。

mounted: function() {
  console.log(this); // Vue
  setInternval(function() {
    console.log(this); // Window
  }, 1000);
  setInterval(() => {
    console.log(this); // Vue
  }, 1000);
}

你有你的爱可信的承诺正确的想法, .then(response => { .. })在使用箭头功能保护的范围this ,但你并没有将其应用到setInterval

如果由于某种原因,你真的很喜欢的外观setInterval(function() { .. })或者你需要this是在Window对象,你可以创建一个变量,并将其分配给this外的setInterval功能。

mounted: function() {
  const vThis = this; // Vue
  setInterval(function() {
    axios({..})
      .then(response => {
        vThis.todos = response.data;
        console.log(this); // Window
        console.log(vThis); // Vue
      })
      .catch(error => {

      });
  }, 5000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM