vue-阻止事件冒泡-開啟右鍵-鍵盤類事件


一: 阻止事件冒泡


 

布局:

  • 當點擊按鈕時,會觸發button的click 也會觸發父級的方法

 

<div id="box">
     <div @click="parentShow">
        <button type="button" @click="show()">按鈕</button>
     </div>
</div>

 

具體實現:

  • 第一種方法,傳入一個event對象,然后對象里有cancelBubble 方法。設置為true

 

<div id="box">
     <div @click="parentShow">
          <button type="button" @click="show($event)">按鈕</button>
     </div>
</div>
methods: {
     show: function(ev){
          alert(1);
          ev.cancelBubble = true;
     },
     parentShow: function(){
          alert(2);
     }
}
  •  第二種方法是vue封裝好的,直接在click的后面加上 .stop,簡單好記,建議使用

 

<div id="box">
     <div @click="parentShow">
           <button type="button" @click.stop="show()">按鈕</button>
     </div>
</div>

 

二:阻止左鍵,開啟右鍵行為


 

  • 按鈕的右鍵行為,vue事件。這里的prevent 是關閉默認行為,相當於    傳個$event   然后 event.preventDefault();

 

<button type="button" @contextmenu.prevent="show1()">按鈕</button>

 

 

三:鍵盤類事件


 

  • keyup、keydown 是監聽鍵盤按下,彈起事件,后面的.enter是指定鍵盤的按鍵,比如常見的:up、down、left、right、enter、tab 等
<input type="text" @keyup.enter="show2()" />
  • 也可以通過$event的keyCode 來獲取鍵盤的值。比如:
<input type="text" @keydown="show2($event)" />
show2: function(ev){
       console.log(ev.keyCode);
}

如果輸入這些,控制台將打印出:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM