vue.once实现
vue.once 的实现方法
在 Vue.js 中,.once 是一个事件修饰符,用于确保事件只触发一次。以下是几种实现方式:
使用事件修饰符
在模板中直接使用 .once 修饰符,可以让事件监听器只触发一次:

<button @click.once="handleClick">Click me</button>
手动实现 once 功能
如果不使用修饰符,可以通过代码手动实现类似功能:

methods: {
handleClick() {
console.log('Button clicked');
this.$off('click', this.handleClick);
}
}
自定义指令实现
可以创建一个自定义指令来实现 .once 的功能:
Vue.directive('once', {
bind(el, binding, vnode) {
const handler = () => {
binding.value();
el.removeEventListener(binding.arg, handler);
};
el.addEventListener(binding.arg, handler);
}
});
使用第三方库
一些第三方库如 lodash 提供了 _.once 方法,可以用来包装函数:
import _ from 'lodash';
methods: {
handleClick: _.once(function() {
console.log('This will only run once');
})
}
这些方法都可以实现事件只触发一次的效果,选择哪种方式取决于具体的使用场景和需求。






