1

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/[email protected]/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?

1 Answer 1

3

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/[email protected]/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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.