[Vuejs]-Vue v-if not affect to Dom when using interval

2👍

// You have lost context in this function, use arrow function instead
.then(function(response) {
  console.log(response);
  if (response.status == 200) {
    this.showtext = true
  }
  console.log(this.showtext)
});

Something like this:

.then(response => {
  console.log(response);
  if (response.status == 200) {
    this.showtext = true
  }
  console.log(this.showtext)
});

3👍

You should use an arrow function like in order to get access to the vue instance scope:

 then((response)=> { ...

or assign this to a global variable as follows (this works with old browsers) :

    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)
              });

Full running example :

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>

2👍

Why my text is not getting rendered ?

because this.showtext that you see on the console is not the one on your $data object … it’s a globlal variable window.showtext because the this bidden to then is window .

solution:

you have to bind your vue instance this instead to your then :

you can do it by using:

then((response) => {}) (which binds this implicitly)

or :

then((function(response) { ... }).bind(this) )

Leave a comment