Vue3项目中autocomplete="off"及"new-password"属性失效问题求助
Vue3 输入框禁用自动填充的可行方案
针对你遇到的autocomplete属性无效、第三方库有readonly遗留问题的情况,给你几个实测有效的解决方法:
利用浏览器特殊属性规避填充
部分浏览器对autocomplete="one-time-code"不会触发自动填充,适合不需要验证码的场景,直接给输入框添加该属性:<input type="password" autocomplete="one-time-code" />优化readonly延迟移除逻辑
你之前的问题是移除readonly后立即触发填充,给移除操作加个微小延迟,避开浏览器的填充时机:<template> <input type="password" :readonly="isReadonly" @focus="handleFocus" /> </template> <script setup> import { ref } from 'vue' const isReadonly = ref(true) const handleFocus = () => { // 延迟100ms移除readonly,既不影响体验又能避开填充 setTimeout(() => { isReadonly.value = false }, 100) } </script>延迟时间可以根据实际情况微调,50-200ms区间都可行。
用假输入框“欺骗”浏览器
浏览器会优先填充匹配类型的输入框,我们可以放一个隐藏的假输入框让浏览器去填充,真实输入框就能躲过:<template> <!-- 隐藏的假输入框,专门用来承接自动填充 --> <input type="text" autocomplete="username" style="position: absolute; left: -9999px; top: -9999px;" tabindex="-1" /> <input type="password" autocomplete="new-password" /> </template>注意给假输入框加
tabindex="-1",避免用户误聚焦到它。随机name/id配合autocomplete="off"
有些浏览器会根据输入框的name/id识别填充目标,给输入框生成随机的name和id,配合autocomplete="off"使用:<template> <input type="password" autocomplete="off" :name="randomInputName" :id="randomInputName" /> </template> <script setup> import { ref, onMounted } from 'vue' const randomInputName = ref('') onMounted(() => { // 生成随机字符串作为name和id randomInputName.value = 'pwd_input_' + Math.random().toString(36).slice(2) }) </script>
内容的提问来源于stack exchange,提问作者Ahmed Allawi
相关产品推荐
相关产品推荐

