使用 vue v-if 后什么时候元素在 dom 中可用
When does an element become available in dom after using vue v-if
使用 vue v-if
后,什么时候元素在 dom 中可用?我原以为您可以在 v-if
计算结果为真后对元素执行查询选择器?
在下面的代码中,我需要在显示弹出窗口后获取 .test
元素,但它显示为 null - 如何获取它?
new Vue({
el: "#app",
data() {
return {
showPopout: false,
};
},
methods: {
buttonClick(day) {
this.showPopout = true;
console.log(document.querySelector('.test'));
},
},
});
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<div id='app'>
<span @click="buttonClick">show popout</span>
<div v-if="showPopout"><span class="test">test</span></div>
</div>
nextTick
后会有
new Vue({
el: "#app",
data() {
return {
showPopout: false,
};
},
methods: {
buttonClick(day) {
this.showPopout = true;
this.$nextTick(() => {
console.log(document.querySelector('.test'));
});
},
},
});
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<div id='app'>
<span @click="buttonClick">show popout</span>
<div v-if="showPopout"><span class="test">test</span></div>
</div>
使用 vue v-if
后,什么时候元素在 dom 中可用?我原以为您可以在 v-if
计算结果为真后对元素执行查询选择器?
在下面的代码中,我需要在显示弹出窗口后获取 .test
元素,但它显示为 null - 如何获取它?
new Vue({
el: "#app",
data() {
return {
showPopout: false,
};
},
methods: {
buttonClick(day) {
this.showPopout = true;
console.log(document.querySelector('.test'));
},
},
});
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<div id='app'>
<span @click="buttonClick">show popout</span>
<div v-if="showPopout"><span class="test">test</span></div>
</div>
nextTick
new Vue({
el: "#app",
data() {
return {
showPopout: false,
};
},
methods: {
buttonClick(day) {
this.showPopout = true;
this.$nextTick(() => {
console.log(document.querySelector('.test'));
});
},
},
});
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<div id='app'>
<span @click="buttonClick">show popout</span>
<div v-if="showPopout"><span class="test">test</span></div>
</div>