this.$nextTick(cb)
cb- - -回调函数,
当页面再次渲染完成后,执行cb回调函数
使用示例:
点击按钮后显示输入框,并且输入框显示时自动获取焦点
代码:
<template>
<div>
<h1>APP根组件</h1>
<input v-if="isVisiable" type="text" ref="inp">
<button v-else @click="showInp">点击隐藏按钮,显示输入框</button>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
isVisiable: false
}
},
methods: {
showInp() {
this.isVisiable = true
// this.$refs.inp.focus() 直接这样写会报错
this.$nextTick(() => {
// console.log(this.$refs.inp);
this.$refs.inp.focus()
})
}
}
}
</script>
this.
r
e
f
s
.
i
n
p
.
f
o
c
u
s
(
)
获
取
焦
点
操
作
要
放
在
t
h
i
s
.
refs.inp.focus() 获取焦点操作要放在 this.
refs.inp.focus()获取焦点操作要放在this.nextTick(cb) 方法中,
因为页面的渲染是异步操作的,当执行 this.isVisiable = true 后,如果立即执行this.
r
e
f
s
.
i
n
p
.
f
o
c
u
s
(
)
,
此
时
页
面
还
没
有
渲
染
出
i
n
p
u
t
输
入
框
,
获
取
不
到
该
元
素
,
所
以
会
报
错
,
将
获
取
焦
点
操
作
放
入
t
h
i
s
.
refs.inp.focus(),此时页面还没有渲染出 input 输入框,获取不到该元素,所以会报错, 将获取焦点操作放入 this.
refs.inp.focus(),此时页面还没有渲染出input输入框,获取不到该元素,所以会报错,将获取焦点操作放入this.nextTick() 函数中后,页面渲染完成后才会执行里面的代码,渲染完成后就有input元素了,所以就可以执行input元素的操作了