首页 > 解决方案 > Vue v-if 使用间隔时不影响 Dom

问题描述

我正在尝试setInterval使用 Vue 进行轮询并有条件地渲染一些元素。但它不起作用,所以我将我的数据设置为true但在 DOM 上什么也没发生。

PS:我使用 Vue.js 和 CDN,所以我的应用程序不是用 VueCLI 创建的。

这是我的 HTML:

<div id="app">
  <div class="container">
    <h1 v-if="showtext">
      text
    </h1>
  </div>
</div>

这是我的脚本。当以状态 200 响应时,我的数据将切换为 true。我可以在控制台上看到它,但我的文本没有在 DOM 上呈现。

var app = new Vue({
  el: "#app",
  data: {
    polling: null,
    showtext: false
  },
  methods: {
    pollData() {
      this.polling = setInterval(() => {
        axios({
          method: "get",
          url: "https://jsonplaceholder.typicode.com/comments"
        }).then(function(response) {
          console.log(response);
          if (response.status == 200) {
            this.showtext = true
          }
          console.log(this.showtext)
        });
      }, 7000);
    }
  },
  beforeDestroy() {
    clearInterval(this.polling);
  },
  created() {
    this.pollData();
  },
});

标签: javascriptvue.jsvuejs2axiosvue-component

解决方案


您应该使用箭头函数来访问 vue 实例范围:

 then((response)=> { ...

this或按如下方式分配给全局变量(这适用于旧浏览器):

    var that=this; ///<------ 
  axios({
                method: "get",
                url: "https://jsonplaceholder.typicode.com/comments"
              }).then(function(response) {
                console.log(response);
                if (response.status == 200) {
                  that.showtext = true
                }
                console.log(that.showtext)
              });

完整运行示例:

Vue.config.devtools = false;
Vue.config.productionTip = false;

     var app = new Vue({
        el: "#app",
        data() {
          return{
          polling: null,
          showtext:false
          }
        },
        methods: {
          pollData() {
            this.polling = setInterval(() => {
              axios({
                method: "get",
                url: "https://jsonplaceholder.typicode.com/comments"
              }).then((response)=> {
               
                if (response.status == 200) {
                  this.showtext = true
                }
                console.log(this.showtext)
              });
            }, 4000);
          }
        },
        beforeDestroy() {
          clearInterval(this.polling);
        },
        created() {
          this.pollData();
        },
      });
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
<div id="app">
      <div class="container">
      test:
        <h1 v-if="showtext">
          text
        </h1>
      </div>
    </div>


推荐阅读