做者:Michael Thiessen前端
譯者:前端小智vue
來源:laracasts.comgit
點贊再看,養成習慣github
本文
GitHub
github.com/qq449245884… 上已經收錄,更多往期高贊文章的分類,也整理了不少個人文檔,和教程資料。歡迎Star和完善,你們面試能夠參照考點複習,但願咱們一塊兒有點東西。面試
本人對這節錄了視頻講解,歡迎點擊:www.ixigua.com/i6790914892…瀏覽器
在作項目時,有時咱們須要讓 input
聚焦,爲了讓用戶更好的使用。微信
全部的瀏覽器都有一個內置的方法,讓 input 聚焦。首先,咱們須要獲取元素。工具
在原生 JS 中,咱們可使用下面方式來獲取元素:this
<form>
<input id="email" />
</form>
const input = document.getElementById('email');
複製代碼
Vue 提供了一個更好的方法:spa
<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 生命週期,讓元素聚焦:
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。
文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub github.com/qq449245884… 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。