gpt4 book ai didi

javascript - 如何在 Vue.js 中调整大小时立即获取元素的宽度和高度

转载 作者:行者123 更新时间:2023-11-30 15:02:38 25 4
gpt4 key购买 nike

Vue.js如何在缩放时立即获取元素的宽高?这是我的码笔插画请帮助我更改它直到工作,谢谢!

Codepen

let app = new Vue({
el: '#app',
data: {
boxs: [{
width: 100,
height: 100
},
{
width: 100,
height: 100
}
]
}

});
#app {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}

.resize {
display: flex;
justify-content: center;
align-items: center;
margin: 5px;
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
background-color: #C3E2CE;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<div id="app">
<div v-for="box,key in boxs" class="resize">
{{ box.width }} x {{ box.height }}
</div>
</div>

最佳答案

要获得响应实际调整大小操作的即时反馈,您可能想尝试使用 MutationObserver .您可以将它附加到组件的 ref 点并在那里监听突变。

您可以在 mounted 函数中附加 MutationObserver。请务必在 destroyed 函数中执行您需要的任何清理工作。

const Resizable = {
template: "<div ref='main' @resize='onResize' class='resize'>{{dims.width}} | {{dims.height}}</div>",
data() {
return {
dims: {
width: null,
height: null
}
};
},
mounted() {
const {
width,
height
} = this.$refs.main.getBoundingClientRect();

this.dims.width = width;
this.dims.height = height;

const mutationHandler = mutationList => {
for (let mutation of mutationList) {
if (mutation.type === "attributes") {
const {
width,
height
} = mutation.target.getBoundingClientRect();

this.dims.width = width;
this.dims.height = height;
}
}
};
const mo = new MutationObserver(mutationHandler);

mo.observe(this.$refs.main, {
attributes: true,
childList: true,
subtree: true
});

},
methods: {
onResize() {
console.log("Resized");
}
}
};

const app = new Vue({
el: "#app",
components: {
"resizable": Resizable
},
data() {
return {
items: [
"foo",
"bar",
"fizz"
]
}
}
});
body {
background-color: #414141;
}

.container {
display: flex;
align-items: center;
justify-content: center;
}

.resize {
resize: both;
margin: 5px;
width: 100px;
height: 100px;
color: black;
overflow: scroll;
background-color: white;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>

<div id="app">
<div class="container">
<resizable v-for="item in items" :key="item" class="resize"></resizable>
</div>
</div>

关于javascript - 如何在 Vue.js 中调整大小时立即获取元素的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46275778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com