vue中弹窗input框聚焦_Vue 中如何让 input 聚焦?(包含视频讲解)
作者:Michael Thiessen
譯者:前端小智
來源:laracasts.com
點贊再看,養成習慣
本文 GitHub https://github.com/qq44924588... 上已經收錄,更多往期高贊文章的分類,也整理了很多我的文檔,和教程資料。歡迎Star和完善,大家面試可以參照考點復習,希望我們一起有點東西。
在做項目時,有時我們需要讓 input 聚焦,為了讓用戶更好的使用。
讓 input 聚焦
所有的瀏覽器都有一個內置的方法,讓 input 聚焦。首先,我們需要獲取元素。
在原生 JS 中,我們可以使用下面方式來獲取元素:
const input = document.getElementById('email');
Vue 提供了一個更好的方法:
const input = this.$refs.email;
獲取元素后,我們就可以讓 input 聚焦了
export default {
methods: {
focusInput() {
this.$refs.email.focus();
}
}
}
如果使用的是自定義組件,則$ref獲取是該組件,而不是我們基礎元素。 因此,如果嘗試讓該組件聚焦,就會報錯。要獲得自定義組件的根元素,我們可以用 $el 訪問:
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 加載好后,才能重新聚焦。
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 https://github.com/qq449245884/xiaozhi 已經收錄,整理了很多我的文檔,歡迎Star和完善,大家面試可以參照考點復習,另外關注公眾號,后臺回復福利,即可看到福利,你懂的。
總結
以上是生活随笔為你收集整理的vue中弹窗input框聚焦_Vue 中如何让 input 聚焦?(包含视频讲解)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java long 对应mybati类型
- 下一篇: mysql custom_MySQL安装