我正在尝试根据组件中元素的宽度设置计算属性。问题是我不知道如何以反应的方式获得宽度。
我在我的元素上有一个参考来获得有效的宽度。但是我似乎无法让 vue 检测到宽度正在变化
我将元素设置为:
<div ref="myDiv"></div>
我的计算属性为:
myProperty() {
return this.$refs.myDiv.clientWidth/2;
}
myProperty 计算正确,但不会随着 myDiv 宽度的变化而变化
我正在尝试根据组件中元素的宽度设置计算属性。问题是我不知道如何以反应的方式获得宽度。
我在我的元素上有一个参考来获得有效的宽度。但是我似乎无法让 vue 检测到宽度正在变化
我将元素设置为:
<div ref="myDiv"></div>
我的计算属性为:
myProperty() {
return this.$refs.myDiv.clientWidth/2;
}
myProperty 计算正确,但不会随着 myDiv 宽度的变化而变化
您可以收听resize事件
data() {
return {
clientWidth: 0
}
},
// bind event handlers to the `handleResize` method (defined below)
mounted: function () {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy: function () {
window.removeEventListener('resize', this.handleResize)
},
methods: {
// whenever the document is resized, re-set the 'clientWidth' variable
handleResize (event) {
if (this.$refs.myDiv) {
this.clientWidth = this.$refs.myDiv.clientWidth
}
}
}
然后你可以使用this.clientWidth你想得到clientWidth的地方。
myProperty() {
return this.clientWidth/2;
}
这个问题的未来读者的另一个选择是使用我创建的一个简单的 mixin https://github.com/Circuit8/vue-computed-dimensions。它为您喜欢的任何 ref 的尺寸和位置创建计算属性,如下面的示例所示:
<template>
<div ref="wrapper">
...
<div ref="other">...</div>
</div>
</template>
<script>
import computedDimensions from "vue-computed-dimensions";
export default {
// computedDimensions accepts a list of refs to use.
// each ref provided will produce 4 computed properties
// in this example we will have wrapperWidth wrapperHeight wrapperX and wrapperY. As well as otherWidth, otherHeight, otherX, and otherY.
// these can then be used in other computed properties to base reactivity on the rendered dimensions of an element
mixins: [computedDimensions("wrapper", "other")],
};
</script>