Vue 中如何讓 input 聚焦?(包含視頻講解)

做者:Michael Thiessen
譯者:前端小智
來源:laracasts.com
點贊再看,養成習慣

本文 GitHub https://github.com/qq44924588... 上已經收錄,更多往期高贊文章的分類,也整理了不少個人文檔,和教程資料。歡迎Star和完善,你們面試能夠參照考點複習,但願咱們一塊兒有點東西。前端

本人對這節錄了視頻講解,歡迎點擊:https://www.ixigua.com/i67909...vue

在作項目時,有時咱們須要讓 input 聚焦,爲了讓用戶更好的使用。git

讓 input 聚焦

全部的瀏覽器都有一個內置的方法,讓 input 聚焦。首先,咱們須要獲取元素。github

在原生 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();
    }
  }
}

可是,若是要在組件加載時就聚焦,要怎麼作呢?this

頁面加載時聚焦

咱們能夠 mouted 生命週期,讓元素聚焦:spa

<template>
<CustomInput ref="email" />
</template>

import CustomInput from './CustomInput.vue';

export default {
  components: {
    CustomInput,
  },
  mounted() {
    this.focusInput();
  },
  methods: {
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}

等待從新渲染

在某些狀況下,咱們可能須要等待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 元素。


代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

原文:https://laracasts.com/discuss...


交流

文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。

相關文章
相關標籤/搜索