温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue中的addEventListener和removeEventListener怎么使用

发布时间:2022-07-02 13:58:29 来源:亿速云 阅读:786 作者:iii 栏目:开发技术

本篇内容介绍了“vue中的addEventListener和removeEventListener怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

addEventListener和removeEventListener用法说明

1、添加监听事件(addEventListener)

语法:element.addEventListener(event, function, useCapture)

  • event:指定事件名(注意: 不要使用 "on" 前缀。 例如,使用 "click" ,而不是使用 "onclick")

  • function:指定要事件触发时执行的函数(事件对象会作为第一个参数传入函数)

  • useCapture:指定事件是否在捕获或冒泡阶段执行,默认false(true - 事件句柄在捕获阶段执行,false-事件句柄在冒泡阶段执行)

mounted() {
    window.addEventListener("resize", this.setNavLeft);
},
methods: {
    listenerFunction(e) {
      document.addEventListener("scroll", this.handleScroll, true);
    },
}

2、移出监听事件(removeEventListener)

语法:element.removeEventListener(event, function, useCapture)

注意:在vue中销毁事件监听,一定要在destroyed生命周期中执行,在 beforeDestroy到destroyed之间,执行组件事件拆卸,在beforeDestroy中执行事件销毁是成功不了的

destroyed() {
    document.removeEventListener("scroll", this.handleScroll, true);
    window.removeEventListener("resize", this.setNavLeft);
  },

使用addEventListener添加事件、removeEventListener移除事件

最近在项目中需要用到addEventListener监听滚动条滚动的高度,所以就研究了一下在vue中是怎么进行事件监听的。

添加事件

给要添加事件的元素加上ref属性

vue中的addEventListener和removeEventListener怎么使用

在mounted中添加事件

    mounted() {
      this.$refs.box.addEventListener('scroll',()=>{
        console.log('scroll',this.$refs.box.scrollTop)
      });
    }

这样就添加成功了!

vue中的addEventListener和removeEventListener怎么使用

移除事件

如果要移除已添加的事件,removeEventListener中传入的方法必须和addEventListener中传入的是同一个方法才能成功移除,所以在添加时就不能用匿名函数啦。需改成如下写法

    mounted() {
      this.$refs.box.addEventListener('scroll',this.scrollEvent);
    },
    methods:{
      scrollEvent(){
        console.log('scroll',this.$refs.box.scrollTop)
      }
    }

这里要注意 传入的方法 this.scrollEvent 后面不能加括号,否则无法成功添加

组件销毁前移除事件

    beforeDestroy() {
      this.$refs.box.removeEventListener('scroll',this.scrollEvent);
    }

如果是keep-alive组件,可以用下面这种方式

  activated() {
    this.$refs.box.addEventListener('scroll', this.scrollEvent);
  },
  deactivated(){
    this.$refs.box.removeEventListener('scroll',this.scrollEvent);
  },

“vue中的addEventListener和removeEventListener怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI