v-resize-observer 检测 DOM 元素的尺寸变化
文档地址 官方文档
安装
npm install v-resize-observer
引入
全局引入
import ResizeObserver from "v-resize-observer";
vue.use(ResizeObserver);
仅引入指令方式 directive
import resizeDirective from "v-resize-observer/src/directive";
export default {
directives: {
resize: resizeDirective,
},
};
仅引入组件方式 component
import ResizeComponent from "v-resize-observer/src/component";
export default {
components: {
ResizeObserver: ResizeComponent,
},
};
注意:如果是按需引入指令或组件,则必须在 vue.config.js 中配置transpileDependencies属性.
module.exports = {
transpileDependencies: [/[/\\]node_modules[/\\]v-resize-observer[/\\]/],
};
使用指令 directive
<div v-resize="hanldResize" />
<div v-resize:debounce="hanldResize" />
<div v-resize:debounce.200="hanldResize" />
<div v-resize:throttle="hanldResize" />
<div v-resize:throttle.200="hanldResize" />
使用组件 component
<ResizeObserver @resize="hanldResize">
<div></div>
</ResizeObserver>
<ResizeObserver
target="#app"
limiter="debounce"
:wait="150"
@resize="hanldResize"
>
<div></div>
</ResizeObserver>
function hanldResize({ width, height }, target) {
console.log(`width: ${width}, height: ${height}`);
}
实操案例(简易 demo)
main.js 文件
import ResizeObserver from "v-resize-observer";
Vue.use(ResizeObserver);
<template>
<div class="resize">
<el-button type="primary" size="default" @click="count += 1"
>添加元素</el-button
>
<div class="box" v-resize="hanldResize">
<div class="item" v-for="item in count" :key="item"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
count: 1,
};
},
methods: {
hanldResize(val) {
console.log("监听元素尺寸变化", val);
},
},
};
</script>
<style lang="scss" scoped>
.resize {
width: 100%;
.box {
width: 100%;
background-color: tomato;
.item {
width: 300px;
height: 400px;
border-radius: 10px;
background-color: pink;
margin: 10px 0;
}
}
}
</style>