官术网_书友最值得收藏!

Event modifiers

Vue makes it easy to listen forspecifickeys by offeringmodifiersto thev-ondirective. Modifiers are postfixes denoted by a dot (.), for example:

<input v-on:keyup.enter="handler">

As you'd probably guess, the.entermodifiertells Vue to only call the handler when the event is triggered by theEnterkey. Modifiers save you from having to remember the specific key code, and also make your template logic more obvious. Vue offers a variety of other key modifiers, including:

  • tab
  • delete
  • space
  • esc

With that in mind, it seems like we could close our modal with this directive:

v-on:keyup.esc="modalOpen = false"

But then what tag do we attach this directive to? Unfortunately, unless an input is focused on, key events are dispatched from thebodyelement, which, as we know, is out of Vue's jurisdiction!

To handle this event we'll, once again, resort to the Web API.

app.js:

var app = new Vue({ 
  ... 
});

document.addEventListener(</span>'keyup', function(evt) { if (evt.keyCode === 27 && app.modalOpen) { app.modalOpen = false; } });

This works, with one caveat (discussed in the next section). But Vue can help us make it perfect.

主站蜘蛛池模板: 长治市| 泾川县| 壤塘县| 南京市| 南溪县| 红安县| 广饶县| 长岛县| 出国| 津市市| 二连浩特市| 巴林左旗| 甘肃省| 广平县| 新蔡县| 宣威市| 高州市| 怀安县| 南城县| 康定县| 通化县| 乐平市| 阳江市| 津市市| 鄂尔多斯市| 汶川县| 安仁县| 革吉县| 武平县| 绵竹市| 阜阳市| 罗平县| 安义县| 张家界市| 山阳县| 沙雅县| 黄浦区| 法库县| 库尔勒市| 永和县| 新邵县|