呈现条件元素后的Vue.js事件

时间:2018-04-18 12:42:30

标签: javascript jquery vue.js vuejs2

我需要事件或一些解决方法如何使用v-if

在jQuery中使用$(".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>

如果我在watch变量上使用showEl,它会在元素渲染之前触发,但我还无法访问该元素。如何在呈现后立即访问.myTarget

1 个答案:

答案 0 :(得分:2)

使用$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>