是否可以v-on:keyup.enter在整个页面上设置一个,而不仅仅是javascript框架中的输入元素Vue.js?
Jam*_*mes 18
也许更好的方法是使用 Vue 组件。这将允许您通过包含或不包含组件来控制何时侦听事件。然后,您可以使用no-ssr 组件将事件侦听器附加到Nuxt。
以下是创建组件的方法:
<template>
<div></div>
</template>
<script>
export default {
created() {
const component = this;
this.handler = function (e) {
component.$emit('keyup', e);
}
window.addEventListener('keyup', this.handler);
},
beforeDestroy() {
window.removeEventListener('keyup', this.handler);
}
}
</script>
<style lang="stylus" scoped>
div {
display: none;
}
</style>
Run Code Online (Sandbox Code Playgroud)
然后在要使用该组件的页面上添加以下 HTML:
<keyboard-events v-on:keyup="keyboardEvent"></keyboard-events>
Run Code Online (Sandbox Code Playgroud)
然后你必须添加你的事件处理程序方法:
methods: {
keyboardEvent (e) {
if (e.which === 13) {
// run your code
}
}
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*den 14
简短回答是肯定的,但具体取决于你的背景.如果您正在使用vue-router,因为我在当前项目中,您可能希望添加到您想要应用的最外层元素.在我的情况下,我正在使用实际的app.vue入口点的初始div元素.
我认为有一个问题是一个很难的要求,元素必须在潜在的可聚焦元素中.我正在处理的方式是设置-1 tabindex并在我的应用程序中的父元素上声明我的超级热键(目前主要用于调试目的).
<template>
<div
id="app-main"
tabindex="-1"
@keyup.enter="doSomething"
>
<everything-else></everything-else>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
编辑:
作为旁注,我还为我的vue-router添加了一些额外的配置,以确保在转换页面时正确的元素被聚焦.这允许基于作为唯一可滚动部分的内容区域将页面调页/页面向下滚动已经在正确的部分中.您还必须将tabindex =" - 1"添加到app-content元素中.
router.afterEach(function (transition) {
document.getElementById('app-content').focus();
});
Run Code Online (Sandbox Code Playgroud)
以及我的app-content组件的基础:
<template>
<div id="app-content" tabindex="-1">
<router-view
id="app-view"
transition="app-view__transition"
transition-mode="out-in"
></router-view>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5543 次 |
| 最近记录: |