Vue 中如何讓 input 聚焦?


在做項目時,有時我們需要讓 input 聚焦,為了讓用戶更好的使用。

 

讓 input 聚焦

所有的瀏覽器都有一個內置的方法,讓 input 聚焦。首先,我們需要獲取元素。

在原生 js 中,我們可以使用下面方式來獲取元素:

<form>
  <input id="email" /> </form> const input = document.getElementById('email'); 

vue 提供了一個更好的方法:

<template>
  <input ref="email" /> </template> const input = this.$refs.email; 

獲取元素后,我們就可以讓 input 聚焦了

<template>
  <input ref="email" /> </template> export default { methods: { focusInput() { this.$refs.email.focus(); } } } 

如果使用的是自定義組件,則$ref獲取是該組件,而不是我們基礎元素。 因此,如果嘗試讓該組件聚焦,就會報錯。要獲得自定義組件的根元素,我們可以用 $el 訪問:

<template>
  <CustomInput ref="email" /> </template> import CustomInput from './CustomInput.vue'; export default { components: { CustomInput, }, methods: { focusInput() { this.$refs.email.$el.focus(); } } } 

但是,如果要在組件加載時就聚焦,要怎么做呢?

 

頁面加載時聚焦

我們可以 mouted 生命周期,讓元素聚焦:

<template> <CustomInput ref="email" /> </template>
import CustomInput from './CustomInput.vue'; export default { components: { CustomInput, }, mounted() { this.focusInput(); }, methods: { focusInput() { this.$refs.email.$el.focus(); } } }

電腦刺綉綉花廠 http://www.szhdn.com 廣州品牌設計公司https://www.houdianzi.com

等待重新渲染

在某些情況下,我們可能需要等待Vue完成整個應用程序的重新渲染。例如,如果將input從隱藏狀態切換到顯示狀態。

因此我們需要等待 input 加載好后,才能重新聚焦。

<template>
  <div> <CustomInput v-if="inputIsVisible" ref="email" /> </div> </template> import CustomInput from './CustomInput.vue'; export default { components: { CustomInput, }, data() { return { inputIsVisible: false, }; }, mounted() { this.focusInput(); }, methods: { showInput() { // Show the input component this.inputIsVisible = true; // Focus the component, but we have to wait // so that it will be showing first. this.nextTick(() => { this.focusInput(); }); }, focusInput() { this.$refs.email.$el.focus(); } } } 

這里,我們在 nextTick 方法中調用 focusInput 方法。因為 nextTick 中表示 Dom 已經加載完成了,所以這時我們才能獲取到 input 元素。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM