我需要事件或一些解决方法如何使用v-if
$(".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
?
答案 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>