文档地址 官方文档
npm install v-resize-observer
import ResizeObserver from "v-resize-observer";
vue.use(ResizeObserver);
import resizeDirective from "v-resize-observer/src/directive";
export default {
directives: {
resize: resizeDirective,
},
};
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[/\\]/],
};
<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" />
<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}`);
}
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>