溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

element-ui?vue?input輸入框自動(dòng)獲取焦點(diǎn)聚焦怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2023-04-18 10:15:07 來源:億速云 閱讀:269 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“element-ui vue input輸入框自動(dòng)獲取焦點(diǎn)聚焦怎么實(shí)現(xiàn)”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“element-ui vue input輸入框自動(dòng)獲取焦點(diǎn)聚焦怎么實(shí)現(xiàn)”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

    element-ui vue input輸入框自動(dòng)獲取焦點(diǎn)聚焦

    element-ui?vue?input輸入框自動(dòng)獲取焦點(diǎn)聚焦怎么實(shí)現(xiàn)

    有時(shí)候會(huì)遇到要輸入框自動(dòng)獲取焦點(diǎn)的情況,解決如下: 

    方法一

    步驟:

    1.在script中寫directives,注冊(cè)一個(gè)全局的自定義指定 v-focus

     directives: {
       focus: {
          inserted: function(el) {
            el.querySelector("input").focus();
          }
        }
     },

    2.在input框直接使用

    <el-input
       ...
      v-focus
    >
    </el-input>

    方法二

    步驟:

    1.給輸入框設(shè)置一個(gè)ref

    <el-input
      ref="saveTagInput"
     >

    2.在需要的時(shí)候操作ref獲取焦點(diǎn)

    this.$refs.saveTagInput.focus();

    vue輸入框自動(dòng)獲取焦點(diǎn)的三種方式

    方式一:原生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方式實(shí)現(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中

    // 注冊(cè)一個(gè)全局自定義指令 `v-focus`
    Vue.directive('focus', {
      // 當(dāng)被綁定的元素插入到 DOM 中時(shí)
      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>

    讀到這里,這篇“element-ui vue input輸入框自動(dòng)獲取焦點(diǎn)聚焦怎么實(shí)現(xiàn)”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI