关键词: vue,$nextTick
关于$nextTick的理解: 若数据的更新与要操作的DOM节点有关,则需要$nextTick;反之则不必。
数据的操作与DOM节点有关
<div id="app">
<input ref="input" type="text" v-if="isEdit" />
<button @click="focusOn">聚焦</button>
</div>
const vm = new Vue({
el: "#app",
data: {
isEdit: false
},
methods: {
focusOn() {
this.isEdit = true;
// this.$refs.input.focus(); // 光标[不会]自动聚焦
this.$nextTick(() => {
this.$refs.input.focus(); // 光标[会]自动聚焦
})
}
}
})
数据的操作与DOM节点无关
<div id="app">
{{number}}
<input ref="input" type="text" />
<button @click="focusOn">聚焦</button>
</div>
const vm = new Vue({
el: "#app",
data: {
number: 0
},
methods: {
focusOn() {
this.number++;
this.$refs.input.focus(); // 光标[会]自动聚焦
}
}
})