Vue $once 函数

1、作用

$once 是一个函数,可以为 vue 实例绑定一个自定义事件,但是这个事件只会被触发一次,触发之后就会被移除。 类似的监听函数有: $on.

2、使用与 $on

(1) $once('xxxx', ()=>{...}) 与 $on('xxx', ()=>{...}) 的用法类似。
(2) $once 只监听一次; $on 一直监听。

3、使用 $once 清除定时器

mounted(){
  let count = 1;
	let timer = setInterval(()=>{
		count++;
	}, count);
	
	this.$once('hook:beforeDestroy', ()=>{
		clearInterval(timer);
		timer = null;
	})
}
Logo

前往低代码交流专区

更多推荐