如何解决Vuetify自动填充导致输入框文本与标签重叠的问题?
该问题的核心是浏览器自动填充表单时,不会触发输入框的input、focus等原生事件,导致Vuetify的v-text-field无法检测到输入框已存在值,不会把label上浮到输入框顶部,才会出现重叠。
方案1:监听自动填充伪类动画(兼容性最好,无延迟)
该方案不会产生肉眼可见的动画延迟,只要浏览器触发自动填充就会立即执行状态更新,不会出现重叠后再修正的闪烁问题。
步骤1:给密码输入框添加ref标识
<template> <v-form> <v-text-field ref="passwordField" type="password" v-model="form.password" label="Password" required ></v-text-field> </v-form> </template>
步骤2:添加自定义CSS触发自动填充检测动画
<style scoped> /* 给自动填充的输入框加一个1ms的无感知动画,用来触发监听 */ input:-webkit-autofill { animation: onAutoFill 0.001s; } @keyframes onAutoFill { from {} to {} } </style>
步骤3:在mounted钩子中监听动画事件,手动触发label上浮
<script> export default { data: () => ({ form: { password: "", }, }), computed: { userData() { return { password: this.form.password, }; }, }, mounted() { const passwordInput = this.$refs.passwordField.$el.querySelector('input') passwordInput.addEventListener('animationstart', (e) => { if (e.animationName === 'onAutoFill') { // 手动设置v-text-field的激活状态,让label上浮 this.$refs.passwordField.isFocused = true // 同步把自动填充的值赋值给绑定的form变量 this.form.password = passwordInput.value } }) } }; </script>
方案2:兜底延迟检测(适配极端浏览器场景)
如果部分老旧浏览器不支持上述动画监听,可以在页面加载完成后延迟500ms检测输入框是否有值,手动触发状态更新:
mounted() { setTimeout(() => { const passwordInput = this.$refs.passwordField.$el.querySelector('input') if (passwordInput.value) { this.$refs.passwordField.isFocused = true this.form.password = passwordInput.value } }, 500) }
内容的提问来源于stack exchange,提问作者Weronika
相关产品推荐
相关产品推荐

