当前位置:首页 > VUE

vue 实现 input focus

2026-01-14 06:16:14VUE

实现 input focus 的方法

在 Vue 中实现 input 元素的 focus 可以通过多种方式完成,以下是几种常见的方法:

使用 ref 和 $refs

通过 ref 属性获取 DOM 元素,并在 mounted 或需要时调用 focus 方法。

<template>
  <input ref="inputRef" />
</template>

<script>
export default {
  mounted() {
    this.$refs.inputRef.focus();
  }
}
</script>

使用 v-focus 自定义指令

创建一个自定义指令 v-focus,自动聚焦元素。

<template>
  <input v-focus />
</template>

<script>
export default {
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      }
    }
  }
}
</script>

通过 $nextTick 确保 DOM 更新

在某些情况下,可能需要等待 DOM 更新完成后再聚焦。

<template>
  <input ref="inputRef" v-if="showInput" />
</template>

<script>
export default {
  data() {
    return {
      showInput: false
    };
  },
  methods: {
    showAndFocus() {
      this.showInput = true;
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    }
  }
}
</script>

动态绑定 focus 状态

通过绑定 :focus 属性实现动态控制。

<template>
  <input :focus="isFocused" @blur="isFocused = false" />
</template>

<script>
export default {
  data() {
    return {
      isFocused: true
    };
  }
}
</script>

使用第三方库

vue-focus 等库可以简化聚焦逻辑。

vue 实现 input focus

<template>
  <input v-focus="true" />
</template>

<script>
import { focus } from 'vue-focus';
export default {
  directives: { focus }
}
</script>

注意事项

  • 确保元素在 DOM 中存在后再调用 focus 方法。
  • 自定义指令适用于需要复用的场景。
  • 动态绑定时需处理 blur 事件以避免状态不一致。

标签: vueinput
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

vue实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标签…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…

vue实现treeselect

vue实现treeselect

Vue TreeSelect 实现方法 使用 Vue 实现 TreeSelect 组件可以通过以下几种方式完成,包括使用现成的第三方库或自行封装组件。 使用第三方库 推荐使用成熟的第三方 TreeS…

vue实现tree

vue实现tree

Vue 实现 Tree 组件 使用 Vue 实现 Tree 组件可以通过递归组件的方式来实现层级结构展示。以下是一个完整的实现方法: 基础递归组件实现 创建 Tree 组件文件 Tree.vue,使…