内容简介::star:️ 更多前端技术和知识点,搜索订阅号文章举例说明一下在 vue 中如何更好的监听浏览器事件。原文介绍了一种新增 vue 实例的方法,单独监听事件。这样代码书写较为简练,容易管理。 :watermelon:
使用 vue 实例更好的监听事件
:star:️ 更多前端技术和知识点,搜索订阅号 JS 菌
订阅
文章举例说明一下在 vue 中如何更好的监听浏览器事件。原文介绍了一种新增 vue 实例的方法,单独监听事件。这样代码书写较为简练,容易管理。 :watermelon:
当监听如下事件的传统做法是:
window.scrollX window.scrollY window.innerHeight window.innerWidth
通常需要书写很多代码:
created () { this.$el.addEventListener('click', this.someMethod) }, destroyed () { this.$el.removeEventListener('click', () => this.someMethod) }
更好的方式是使用新的 Vue 实例
import Vue from 'vue' const WindowInstanceMap = new Vue({ data() { return { scrollY: 0 } }, created() { window.addEventListener('scroll', e => { this.scrollY = window.scrollY }) }, }) export default WindowInstanceMap
然后在项目中使用:
// AppNav.vue import WindowInstanceMap from './WindowInstanceMap.js' export default { computed: { scrollY () { return WindowInstanceMap.scrollY }, isCollapsed () { return this.scrollY < 100 } } }
这样做的好处是:
- 不会大量占用 dev-tool 的版面显示变动信息
- 减少主要项目的代码
- 因为 dev-tool 不支持多实例的调试,因此需要对这部分代码保持简单
最后看看效果:
参考这篇文章: Reactive Window Parameters in VueJS 可以阅读原文查看详细介绍。
请关注我的订阅号,不定期推送有关 JS 的技术文章,只谈技术不谈八卦 :blush:
以上所述就是小编给大家介绍的《使用 vue 实例更好的监听事件》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Blockchain Basics
Daniel Drescher / Apress / 2017-3-16 / USD 20.99
In 25 concise steps, you will learn the basics of blockchain technology. No mathematical formulas, program code, or computer science jargon are used. No previous knowledge in computer science, mathema......一起来看看 《Blockchain Basics》 这本书的介绍吧!