当你在 Vue 中更改响应式状态时,最终的 DOM 更新并不是同步生效的,而是由 Vue 将它们缓存在一个队列中,直到下一个“tick”才一起执行。这样是为了确保每个组件无论发生多少状态改变,都仅执行一次更新。
nextTick()
可以在状态改变后立即使用,以等待 DOM 更新完成。你可以传递一个回调函数作为参数,或者 await 返回的 Promise。
以“点击编辑,显示编辑框并且自动获取焦点”为例
先准备好基础页面,并且将内容渲染至页面
现在就是这样的效果
然后来给编辑按钮注册点击事件
并且用methods提供一个方法
handelEdit()
点击编辑按钮,触发事件,显示input框
当显示完成之后,要注意用this.$refs.inp.focus()是不能成功的。此时就需要我们 $nextTick 登场了
原因:Vue是异步更新DOM(提升性能)
$nextTick 等DOM更新后,才会触发执行此方法里的函数体
this.$nextTick(() => {})
下面是完整代码,参考一下
<template>
<div class="app">
<!-- 是否在编辑状态 -->
<div v-if="isShow">
<input type="text" v-model="inpValue" ref="inp">
<button>确认</button>
</div>
<!-- 默认状态 -->
<div v-else>
<span>{{ title }}</span>
<button class="edit" @click="handelEdit">编辑</button>
</div>
</div>
</template>
<script>
export default {
data(){
return{
isShow:false,
inpValue:'',
title:'点击',
}
},
methods:{
handelEdit(){
// 1.显示输入框 (异步dom更新)
// console.log('触发handelEdit()');
this.isShow=true;
// 2.让输入框 获取焦点 ($nextTick等dom更新完,立刻执行准备的函数体)
this.$nextTick(() => {
// console.log(this.$refs.inp);
this.$refs.inp.focus()
})
}
}
}
</script>
<style scoped>
button{
margin: 10px;
}
span,.edit{
margin: 10px 0 0 50px;
}
</style>