返回

打造无忧无虑的表单输入体验:完美解决element-ui密码输入框自动填充

前端

密码输入框自动填充的烦恼

在使用element-ui时,您可能会遇到密码输入框自动填充的问题。当您点击密码输入框时,浏览器会自动弹出密码填充建议,这不仅不安全,而且会影响用户体验。

完美解决方案:setTimeout 0

为了完美解决element-ui密码输入框自动填充的问题,我们可以使用setTimeout 0的延时技巧。具体做法如下:

<template>
  <el-input type="password" v-model="password" @focus="handleFocus" />
</template>

<script>
export default {
  data() {
    return {
      password: ''
    }
  },
  methods: {
    handleFocus() {
      setTimeout(() => {
        this.$refs.input.focus()
      }, 0)
    }
  }
}
</script>

在上面的代码中,我们在el-input组件上绑定了@focus事件,当密码输入框获得焦点时,会触发handleFocus方法。在这个方法中,我们使用了setTimeout 0的延时技巧来延迟执行this.$refs.input.focus()。这样一来,当浏览器尝试自动填充密码时,密码输入框已经失去了焦点,因此不会出现自动填充建议。

注意事项

需要注意的是,上述解决方案还不算完全解决问题。在某些情况下,当密码输入框为空时点击或多次点击,仍然会弹出密码填充框。为了完全解决这个问题,您还可以添加mousedown事件来阻止浏览器的自动填充行为。

<template>
  <el-input type="password" v-model="password" @focus="handleFocus" @mousedown="handleMousedown" />
</template>

<script>
export default {
  data() {
    return {
      password: ''
    }
  },
  methods: {
    handleFocus() {
      setTimeout(() => {
        this.$refs.input.focus()
      }, 0)
    },
    handleMousedown() {
      this.$refs.input.focus()
    }
  }
}
</script>

结论

通过使用setTimeout 0的延时技巧和mousedown事件,我们完美地解决了element-ui密码输入框自动填充的问题。现在,您可以放心使用element-ui来构建表单,而无需担心密码输入框自动填充的烦恼。