指令源码
function addEventListner(el, binding) {
// el为绑定的元素,binding为绑定给指令的对象
let width = '';
let height = '';
function isReize() {
const rect = el.getBoundingClientRect();
if (width !== rect.width || height !== rect.height) {
// 关键(这传入的是函数,所以执行此函数)
binding.value(rect);
}
width = rect.width;
height = rect.height;
}
// eslint-disable-next-line no-underscore-dangle
el.__vueSetInterval__ = setInterval(isReize, 300);
}
export default {
install(Vue) {
Vue.directive('resize', {
bind(el, binding, a) {
if (!el) return;
console.log('注册 resize 事件', el, binding, a);
addEventListner(el, binding);
},
unbind(el) {
if (!el) return;
console.log(el, '解绑 resize 事件');
// eslint-disable-next-line no-underscore-dangle
clearInterval(el.__vueSetInterval__);
}
});
}
};
注册自定义指令
import resize from '@/directives/resize';
Vue.use(resize);
使用自定义指令
<template>
<div
class="game-tools"
v-resize="onResize"
></div>
</template>
<script>
...,
methods: {
onResize({height, width}) {
console.log('尺寸发生变化')
}
}
</script>