将原生JS鼠标事件转换为Vue中的事件处理
在Vue中,可以将原生JS的鼠标事件转换为以下形式:
export default {
mounted() {
const img = document.querySelector('.img');
img.addEventListener('mouseenter', this.mouseEnter);
img.addEventListener('mousemove', this.mouseMove);
},
methods: {
mouseEnter(e) {
this.x = e.clientX;
this.y = e.clientY;
},
mouseMove(e) {
this._x = e.clientX;
this._y = e.clientY;
const disx = this._x - this.x;
const disy = this._y - this.y;
const movex = disx * 2;
const movey = -600 + disy / 1.6;
const img = document.querySelector('.img');
img.style.backgroundPosition = `${movex}px ${movey}px`;
}
}
}
在Vue中,可以在mounted生命周期钩子函数中监听事件,并在methods中定义mouseEnter和mouseMove方法来处理事件。同时,可以使用this关键字来访问Vue实例中的数据和方法。
原文地址: http://www.cveoy.top/t/topic/nOhK 著作权归作者所有。请勿转载和采集!