Vue $nextTick 解决 v-if 切换后操作 DOM 报错问题
Vue 大约 794 字场景
控制v-if
的inputVisible
变量来显示input
输入框,但输入框显示后需要获取焦点。
<template>
<div>
<div>
<input v-if="inputVisible" ref="inputRef" type="text" placeholder="请输入">
</div>
<button @click="showInput">展示按钮</button>
</div>
</template>
$nextTick
如果直接在改变v-if
可见性后对DOM
进行操作会报错,因为此时DOM
还没开始渲染,还没开始走updated
生命周期。
使用this.$nextTick(callback function)
接收DOM
渲染完毕的回调,在回调函数中对元素进行操作。
export default {
name: "NextTick",
data: () => ({
inputVisible: false
}),
methods: {
showInput() {
this.inputVisible = true
// DOM渲染完毕才能执行,因为此时生命周期还没走到渲染 input 组件
// this.$refs.inputRef.focus()
// this.$nextTick 等到 DOM 渲染完毕才执行 callback 中的回调
this.$nextTick(()=>{
this.$refs.inputRef.focus()
})
}
}
}
阅读 814 · 发布于 2022-12-26
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Go 数组和切片阅读 1545
-
不同平台文件格式:dos、unix、mac阅读 6472
-
Spring Boot OpenFeign IllegalStateException: RequestParam.value() was empty on parameter 0阅读 1253
-
IDEA 破解后打不开解决方法阅读 16533
-
Vue v-pre 加载 {{}}阅读 445
-
VirtualBox 安装 Alpine Linux阅读 1077
-
OpenResty 常用 HTTP 请求 API阅读 5501
-
macOS 解决 ApacheDirectoryStudio 无法启动问题阅读 474
-
MySQL 规约阅读 4021
-
Kubernetes ConfigMap 创建失败 cannot unmarshal number into Go struct field ConfigMap.data of type string阅读 2994