element-ui vue input輸入框自動獲取焦點聚焦方式
更新時間:2023年04月17日 16:16:02 作者:違規(guī)昵稱001
這篇文章主要介紹了element-ui vue input輸入框自動獲取焦點聚焦方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
element-ui vue input輸入框自動獲取焦點聚焦

有時候會遇到要輸入框自動獲取焦點的情況,解決如下:
方法一
步驟:
1.在script中寫directives,注冊一個全局的自定義指定 v-focus
directives: {
focus: {
inserted: function(el) {
el.querySelector("input").focus();
}
}
},
2.在input框直接使用
<el-input ... v-focus > </el-input>
方法二
步驟:
1.給輸入框設(shè)置一個ref
<el-input ref="saveTagInput" >
2.在需要的時候操作ref獲取焦點
this.$refs.saveTagInput.focus();
vue輸入框自動獲取焦點的三種方式
方式一:原生JS操作DOM
<template>
? <div class="focusDemo">
? ? <input type="text" v-model="username" id='inputId'/>
? </div>
</template>
<script>
export default {
? data () {
? ? return {
? ? ? username: ''
? ? }
? },
? mounted () {
? ? document.getElementById('inputId').focus()
? }
}
</script>方式二:ref方式實現(xiàn)
<template>
? <div class="focusDemo">
? ? <input ref="inputName" type="text" v-model="username" />
? </div>
</template>
<script>
export default {
? data () {
? ? return {
? ? ? username: ''
? ? }
? },
? mounted () {
? ? this.$nextTick(() => {
? ? ? this.$refs.inputName.focus()
? ? })
? }
}
</script>方式三:使用自定義指令
main.js中
// 注冊一個全局自定義指令 `v-focus`
Vue.directive('focus', {
? // 當(dāng)被綁定的元素插入到 DOM 中時
? inserted: function (el) {
? ? // 聚焦元素
? ? el.focus()
? },
? update: function (el) {
? ? // 聚焦元素
? ? el.focus()
? }
})vue文件中
<template>
? <div class="focusDemo">
? ? <input type="text" v-model="username" v-focus />
? </div>
</template>
<script>
export default {
? data () {
? ? return {
? ? ? username: ''
? ? }
? }
}
</script>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- vue如何動態(tài)獲取當(dāng)前時間
- vue怎樣獲取當(dāng)前時間,并且傳遞給后端(不用注解)
- vue 使用moment獲取當(dāng)前時間及一月前的時間
- Vue 中如何利用 new Date() 獲取當(dāng)前時間
- 基于vue實現(xiàn)8小時帶刻度的時間軸根據(jù)當(dāng)前時間實時定位功能
- vue中實現(xiàn)當(dāng)前時間echarts圖表時間軸動態(tài)的數(shù)據(jù)(實例代碼)
- Vue 按照創(chuàng)建時間和當(dāng)前時間顯示操作(剛剛,幾小時前,幾天前)
- Vue 中獲取當(dāng)前時間并實時刷新的實現(xiàn)代碼
- Vue filter 過濾當(dāng)前時間 實現(xiàn)實時更新效果
- vue 2.1.3 實時顯示當(dāng)前時間,每秒更新的方法
- Vue3新增時自動獲取當(dāng)前時間的操作方法
相關(guān)文章
Vite中自制mock服務(wù)器(不使用第三方服務(wù))
本文主要介紹了Vite中自制mock服務(wù)器,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
vue3使用Pinia的store的組件化開發(fā)模式詳解
這篇文章主要介紹了vue3使用Pinia的store的組件化開發(fā)模式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
vue中實現(xiàn)點擊按鈕滾動到頁面對應(yīng)位置的方法(使用c3平滑屬性實現(xiàn))
這篇文章主要介紹了vue中實現(xiàn)點擊按鈕滾動到頁面對應(yīng)位置的方法,這段代碼主要使用c3平滑屬性實現(xiàn),需要的朋友可以參考下2019-12-12

