一篇文章教你實(shí)現(xiàn)VUE多個(gè)DIV,button綁定回車(chē)事件
目前有個(gè)需求是這樣的,點(diǎn)擊確定按鈕或鍵盤(pán)回車(chē)時(shí)執(zhí)行操作,很多地方都需要用到。
試了幾種方法均不行,
首先,我在div(button也一樣)上 綁定@keyup.enter方法,完全沒(méi)效果,然后按照網(wǎng)上的方法,這樣寫(xiě):
<div class="btn submit" @keyup.enter="submit" @click="submit">確定(Ent)</div>
created(){ document.onkeydown = function(e) { if(e.keyCode == 13){ console.log("調(diào)用需要執(zhí)行的方法"); } } },
這樣確實(shí)可以實(shí)現(xiàn)回車(chē)事件,但是這是全局的,也就是說(shuō),你在其他組件回車(chē)時(shí)也會(huì)調(diào)用此處的回車(chē)事件,此方法不行。
然后我是這樣做的:
1.在確定按鈕和取消按鈕中間添加個(gè)<input>標(biāo)簽(放在中間可以當(dāng)按鈕的間隔,就不用寫(xiě)margin-left了),然后給這個(gè)input標(biāo)簽加上@keyup.enter事件;
<template slot="footer"> <div class="dialog-footer dis-flex"> <div class="btn cancel" @click="showDialog = false">取消(Esc)</div> <input type="text" ref="inputdata" class="hiddenIpt" @keyup.enter="submit" /> <div class="btn submit" @click="submit"> 確定(Ent) </div> </div> </template>
2.寫(xiě)個(gè)監(jiān)聽(tīng)器,監(jiān)聽(tīng)到彈窗打開(kāi)時(shí),給input框自動(dòng)聚焦( inputdata 是 input 上用 ref 綁定的)。
watch: { showDialog() { if (this.showDialog) { //this.$refs.inputdata.focus(); 錯(cuò)誤寫(xiě)法 this.$nextTick(() => {//正確寫(xiě)法 this.$refs.inputdata.focus(); }); } }, },
3.隱藏input框(設(shè)置寬度用來(lái)當(dāng)確定按鈕和取消按鈕之間的間隔。)
.hiddenIpt { width: 2rem; opacity: 0; }
就這樣完美解決,有更好的辦法,歡迎溝通交流。
總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
vue3?reactive響應(yīng)式依賴收集派發(fā)更新原理解析
這篇文章主要為大家介紹了vue3響應(yīng)式reactive依賴收集派發(fā)更新原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03vue3.x對(duì)echarts的二次封裝之按需加載過(guò)程詳解
echarts是我們后臺(tái)系統(tǒng)中最常用的數(shù)據(jù)統(tǒng)計(jì)圖形展示,外界對(duì)它的二次封裝也不計(jì)層數(shù),這篇文章主要介紹了vue3.x對(duì)echarts的二次封裝之按需加載,需要的朋友可以參考下2023-09-09