Rashid
Rashid

Reputation: 1750

Vuejs conditional rendering v-if

I have this part of code wherein in my view theres a condition if I want to show it or not

<div v-if="toShow" ref="target"></div>

and in my javascript code I trigger toShow to true

this.toShow = true

this.$refs.target // always null

but when I use setTimeout() the value is not null

I need a solution wherein I dont want to use setTimeout() because I'm toggling toShow everytime for my transition so what happens is a have a lot of nested setTimeout() in my code.

Upvotes: 1

Views: 371

Answers (1)

Shoejep
Shoejep

Reputation: 4849

You can use $nextTick which waits until the next DOM update cycle. It should be much better than setTimeout because it gets called quickly after the DOM updates rather than a specific time later.

I've created a fiddle below showing it working.

new Vue({
  el: "#app",
  data: () => {
    return {
      show: false
    };
  },
  methods: {

    toggleShow() {
      this.show = !this.show;
      console.log(this.$refs.target);

      this.$nextTick(() => {
        console.log(this.$refs.target);
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="toggleShow">Toggle Show</button>

  <div v-if="show">
    <h5>Showing</h5>
    <div ref="target"></div>
  </div>
</div>

Upvotes: 2

Related Questions