天天看點

input不管用 vue_Vue 中如何讓 input 聚焦?(包含視訊講解)

下面是本人對這節錄的視訊講解,歡迎點選觀看

在做項目時,有時我們需要讓

input

聚焦,為了讓使用者更好的使用。

讓 input 聚焦

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

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

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

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

擷取元素後,我們就可以讓

input

聚焦了

如果使用的是自定義元件,則

$ref

擷取是該元件,而不是我們基礎元素。是以,如果嘗試讓該元件聚焦,就會報錯。要獲得自定義元件的根元素,我們可以用

$el

通路:

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

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

頁面加載時聚焦

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

等待重新渲染

在某些情況下,我們可能需要等待Vue完成整個應用程式的重新渲染。例如,如果将

input

從隐藏狀态切換到顯示狀态。

是以我們需要等待

input

加載好後,才能重新聚焦。

<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 componentthis.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

元素。

作者:Michael Thiessen 譯者:前端小智 來源:laracasts.com

原文:https://laracasts.com/discuss/channels/vue/vue-set-focus-to-input-created-by-v-for?page=1

交流

input不管用 vue_Vue 中如何讓 input 聚焦?(包含視訊講解)

如何在 Vue 中使用 JSX 以及使用它的原因

視訊課|在Vue中強制元件重新渲染的幾中方法

如何在Vue中動态添加類名