当前位置:首页 > VUE

vue 实现获取焦点

2026-03-07 23:44:27VUE

Vue 实现获取焦点的方法

在 Vue 中实现获取焦点可以通过多种方式,以下是几种常见的实现方法:

使用 ref 和 $refs

通过 ref 属性标记元素,然后在方法中调用 focus() 方法:

<template>
  <input ref="inputRef" />
  <button @click="focusInput">获取焦点</button>
</template>

<script>
export default {
  methods: {
    focusInput() {
      this.$refs.inputRef.focus()
    }
  }
}
</script>

使用 v-focus 自定义指令

创建一个自定义指令来自动聚焦元素:

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

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

使用 autofocus 属性

对于简单的场景,可以直接使用 HTML5 的 autofocus 属性:

<template>
  <input autofocus />
</template>

在 mounted 钩子中获取焦点

当组件挂载完成后自动获取焦点:

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

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

使用 nextTick 确保 DOM 更新

在某些需要等待 DOM 更新的情况下使用:

vue 实现获取焦点

<template>
  <input ref="inputRef" v-if="showInput" />
  <button @click="showInput = true">显示并聚焦输入框</button>
</template>

<script>
export default {
  data() {
    return {
      showInput: false
    }
  },
  watch: {
    showInput(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.$refs.inputRef.focus()
        })
      }
    }
  }
}
</script>

以上方法可以根据具体需求选择使用,ref 方式最为灵活,自定义指令适合需要复用的场景,autofocus 属性最简单但有限制。

标签: 焦点vue
分享给朋友:

相关文章

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed: {…

vue实现选中单元格

vue实现选中单元格

Vue 实现选中单元格的方法 基础实现思路 在 Vue 中实现选中单元格功能,通常可以通过动态绑定 class 或 style 来实现。以下是一个基于表格的简单实现示例: <template&…

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted 和…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue实现list

vue实现list

Vue 实现列表渲染 在 Vue 中,可以使用 v-for 指令来渲染列表。v-for 指令基于一个数组或对象来渲染一个列表,可以遍历数组或对象的属性。 基本列表渲染 <template>…

vue实现卡片

vue实现卡片

Vue 实现卡片组件的方法 使用 Vue 实现卡片组件可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 HTML 和 CSS 在 Vue 单文件组件中,可以通过模板和样式直接实现卡片效果…