一篇文章教你實現(xiàn)VUE多個DIV,button綁定回車事件
目前有個需求是這樣的,點擊確定按鈕或鍵盤回車時執(zhí)行操作,很多地方都需要用到。

試了幾種方法均不行,
首先,我在div(button也一樣)上 綁定@keyup.enter方法,完全沒效果,然后按照網(wǎng)上的方法,這樣寫:
<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í)行的方法");
}
}
},
這樣確實可以實現(xiàn)回車事件,但是這是全局的,也就是說,你在其他組件回車時也會調(diào)用此處的回車事件,此方法不行。
然后我是這樣做的:
1.在確定按鈕和取消按鈕中間添加個<input>標簽(放在中間可以當按鈕的間隔,就不用寫margin-left了),然后給這個input標簽加上@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.寫個監(jiān)聽器,監(jiān)聽到彈窗打開時,給input框自動聚焦( inputdata 是 input 上用 ref 綁定的)。
watch: {
showDialog() {
if (this.showDialog) {
//this.$refs.inputdata.focus(); 錯誤寫法
this.$nextTick(() => {//正確寫法
this.$refs.inputdata.focus();
});
}
},
},
3.隱藏input框(設(shè)置寬度用來當確定按鈕和取消按鈕之間的間隔。)
.hiddenIpt {
width: 2rem;
opacity: 0;
}
就這樣完美解決,有更好的辦法,歡迎溝通交流。



總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
基于Vue + Axios實現(xiàn)全局Loading自動顯示關(guān)閉效果
在vue項目中,我們通常會使用Axios來與后臺進行數(shù)據(jù)交互,而當我們發(fā)起請求時,常常需要在頁面上顯示一個加載框(Loading),然后等數(shù)據(jù)返回后自動將其隱藏,本文介紹了基于Vue + Axios實現(xiàn)全局Loading自動顯示關(guān)閉效果,需要的朋友可以參考下2024-03-03

