Skip to content
Advertisement

Vue.js event after condition element is rendered

I need event or some workaround how to access currently appended element with v-if in jQuery with $(".myTarget")

var vue = new Vue({
  el: '#vue',
  data: {
    showEl : false,
  },
  watch: {
    showEl: function (newShowEl, oldShowEl) {
      console.log("Watch event: " + $(".myTarget")[0]); 
    }
  },
  methods: {
    toggleMyTarget: function () {
      vue.showEl = !vue.showEl;
      console.log("Toggle on click event: " + $(".myTarget")[0]); 
    }
  },
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="vue">
  <div v-if="showEl">
    <span class="myTarget">My element</span>
  </div>

  <button @click="toggleMyTarget">Toggle element</button>
</div>

if I use watch on showEl variable it triggers before element renders and I can’t access that element yet. How to achieve to be able to access .myTarget immediately after it renders?

Advertisement

Answer

Use $nextTick.

var vue = new Vue({
  el: '#vue',
  data: {
    showEl : false,
  },
  watch: {
    showEl: function (newShowEl, oldShowEl) {
      this.$nextTick(() => console.log("Watch event: " + $(".myTarget")[0]))
    }
  },
  methods: {
    toggleMyTarget: function () {
      vue.showEl = !vue.showEl;
      this.$nextTick(() => console.log("Toggle on click event: " + $(".myTarget")[0]))
    }
  },
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="vue">
  <div v-if="showEl">
    <span class="myTarget">My element</span>
  </div>

  <button @click="toggleMyTarget">Toggle element</button>
</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement