在 Vue.js 中处理全局事件

Vue 的事件处理方法很棒. 只需将一个元素的@eventName="eventHandler``属性扔到一个元素上,然后叫它一天。 然而,此类便利性默认情况下不会扩展到全球事件中。 您需要使用addEventListener`的试验和真实方法。 或者,您可以使用由 Damian DuliszEduardo San Martin Morote带给您的这款非常方便的小Vue组件。

安装

1# Yarn
2$ yarn vue-global-events
3# NPM
4$ npm install vue-global-events --save

使用

现在在main.js 中安装该组件。

 1[label main.js]
 2import Vue from 'vue';
 3import App from './App.vue';
 4import GlobalEvents from 'vue-global-events';
 5
 6// You can also import it individually per-component.
 7Vue.component(GlobalEvents);
 8
 9new Vue({
10  el: '#app',
11  render: h => h(App)
12});

现在,您可以从任何组件中听到 所有类型的全球事件,同时仍然使用Vue的清晰而简单的语法. 您甚至不必担心删除事件! 您还可以使用v-if和相关指令来启用和禁用处理器。

 1<template>
 2  <div>
 3    <GlobalEvents
 4      @blur="handleAppBlur"
 5      @focus="handleAppFocus"
 6      @keydown.ctrl.tab="handleTabChange"
 7    ></GlobalEvents>
 8    <!-- The rest of your component -->
 9  </div>
10</template>
11
12<script>
13export default {
14  methods: {
15    handleAppFocus() {
16      console.log(`I've been focused!`);
17    },
18
19    handleAppBlur() {
20      console.log(`I'm feeling a bit blurry...`);
21    },
22
23    handleTabChange() {
24      console.log(`**Doing Tab Changy Things**`);
25    }
26  }
27}
28</script>
Published At
Categories with 技术
Tagged with
comments powered by Disqus