vue 实现 input focus
Vue 实现 input focus 的方法
使用 ref 和 $refs
在 Vue 中可以通过 ref 和 $refs 来获取 DOM 元素并调用其 focus() 方法。
<template>
<input ref="inputRef" type="text" />
<button @click="focusInput">Focus Input</button>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.inputRef.focus();
}
}
};
</script>
使用 v-model 和 nextTick
如果需要自动聚焦输入框,可以在组件挂载后使用 nextTick 确保 DOM 已渲染。
<template>
<input v-model="inputValue" ref="inputRef" type="text" />
</template>
<script>
export default {
data() {
return {
inputValue: ''
};
},
mounted() {
this.$nextTick(() => {
this.$refs.inputRef.focus();
});
}
};
</script>
使用自定义指令
可以创建一个自定义指令 v-focus 来实现自动聚焦。
<template>
<input v-focus type="text" />
</template>
<script>
export default {
directives: {
focus: {
inserted(el) {
el.focus();
}
}
}
};
</script>
使用 Composition API (Vue 3)
在 Vue 3 中,可以使用 ref 和 onMounted 来实现类似功能。
<template>
<input ref="inputRef" type="text" />
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const inputRef = ref(null);
onMounted(() => {
inputRef.value.focus();
});
return {
inputRef
};
}
};
</script>
动态聚焦多个输入框
如果需要动态控制多个输入框的聚焦状态,可以通过动态绑定 ref 和条件判断来实现。
<template>
<input v-for="(item, index) in items" :key="index" :ref="`input${index}`" type="text" />
<button @click="focusInput(0)">Focus First Input</button>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3]
};
},
methods: {
focusInput(index) {
this.$refs[`input${index}`][0].focus();
}
}
};
</script>
注意事项
- 确保 DOM 已渲染完成后再调用
focus(),否则可能无法生效。 - 在 Vue 3 中,
$refs是响应式的,可以直接通过ref变量访问。 - 自定义指令可以复用,适合需要多次聚焦的场景。







