English | 简体中文
Vue普通元素resize事件监听,借鉴自Cross-Browser, Event-based, Element Resize Detection
- Vue3.0
npm install --save vue-resize-observer@next
- Vue2.0
npm install --save vue-resize-observer
- 在入口文件(比如:
main.js
)中引入并use
const VueResizeObserver = require("vue-resize-observer");
Vue.use(VueResizeObserver);
// Vue3.0
const app = createApp(App)
app.use(VueResizeObserver) // use is a instance's method & be called before mount
app.mount('#app')
// Vue2.0
Vue.use(VueResizeObserver); // use is a static method
or
import VueResizeObserver from "vue-resize-observer";
Vue.use(VueResizeObserver);
// Vue3.0
const app = createApp(App)
app.use(VueResizeObserver) // use is a instance's method & be called before mount
app.mount('#app')
// Vue2.0
Vue.use(VueResizeObserver); // use is a static method
- Then
v-resize
directive to detect DOM resize events.
<template>
<div class="resize" v-resize="onResize">
width: {{width}}, height: {{height}}
</div>
</template>
<script>
export default {
data() {
return {
// Vue2.0
Vue.use(VueResizeObserver); // use is a static method
或者
import VueResizeObserver from "vue-resize-observer";
Vue.use(VueResizeObserver);
// Vue3.0
app.use(VueResizeObserver) // use is a instance's method
// Vue2.0
Vue.use(VueResizeObserver); // use is a static method
或者
import VueResizeObserver from "vue-resize-observer";
// Vue3.0
Vue.createApp({
directives: { 'resize': VueResizeObserver },
})
// Vue2.0
new Vue({
directives: { 'resize': VueResizeObserver },
})
- 在组件元素中使用
v-resize
<template>
<div class="resize" v-resize="onResize">
width: {{width}}, height: {{height}}
</div>
</template>
<script>
export default {
data() {
return {
width: 0,
height: 0,
}
},
mounted() {
this.width = this.$el.offsetWidth;
this.height = this.$el.offsetHeight;
},
methods: {
onResize({ width, height }) {
this.width = width;
this.height = height;
}
}
}
</script>
<style>
.resize {
background-color: orange;
width: 300px;
height: 300px;
margin: 0 auto;
resize: both;
overflow: auto;
display: flex;
justify-content: center;
align-items: center;
}
</style>
- 运行
npm run dev
- 文档生成
npm run doc
或者阅读在线文档
- 打开位于
docs
的index.html
即可查看开发文档
在当前元素的position
有且只有在static
的情况下,会改变当前元素的position
属性为relative
,所以对此属性敏感的元素需要谨慎对待!