Vue生命周期的created()钩⼦函数进行的DOM操作⼀定要放在Vue.nextTick()的回调函数中, 因为此时DOM还没有渲染,当项目中改变data函数的数据,想基于新的dom做点什么,对新DOM⼀系列的js操作都需要放进Vue.nextTick()的回调函数中
具体场景
需求:点击编辑后显示input框并自动获取焦点
不能直接写获取元素后执行焦点事件, 因为DOM的更新是异步的
<template>
<div class="app">
<div v-if="isShowEdit">
<input type="text" v-model="editValue" ref="inp" />
<button>确认</button>
</div>
<div v-else>
<span>{{ title }}</span>
<button @click="editFn">编辑</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
title: '大标题',
isShowEdit: false,
editValue: '',
}
},
methods: {
editFn() {
// 1.显示文本框
this.isShowEdit = true
// 2.让文本框聚焦
// 在 vue 中数据变化视图会更新, 关键点: 视图的更新是异步任务, 因为更新前可能要执行一些操作, 不能一变化就立马更新, 为了性能优化, 视图的更新就是异步的
// 不能直接写获取元素后执行焦点事件, 因为DOM的更新是异步的,
// 方法一: 使用定时器, 但是定时器是宏任务
// this.$refs.inp.focus()
// vue 为我们准备了, $nextTick(), 里面可以写一个回调函数, 这个回调函数就是在DOM更新后才执行的
this.$nextTick(()=>{
// 此回调函数在DOM更新后才会执行
this.$refs.inp.focus()
})
},
},
}
</script>