HTML 结构:
<div id="app">
<div class="div1" :style="{ height: maxHeight + 'px' }">Content 1</div>
<div class="div2" :style="{ height: maxHeight + 'px' }">Content 2</div>
</div>
Vue.js 代码:
new Vue({
el: '#app',
data: {
maxHeight: 0
},
mounted() {
this.updateHeight();
window.addEventListener('resize', this.updateHeight);
},
beforeDestroy() {
window.removeEventListener('resize', this.updateHeight);
},
methods: {
updateHeight() {
const div1 = this.$el.querySelector('.div1');
const div2 = this.$el.querySelector('.div2');
const maxHeight = Math.max(div1.offsetHeight, div2.offsetHeight);
this.maxHeight = maxHeight;
}
}
});
我定义了一个 Vue 实例,并将其绑定到 #app
元素上。通过在实例的 data
中定义 maxHeight
属性
在 mounted
钩子函数中,调用 updateHeight
方法来初始化 maxHeight
值,并监听窗口的 resize
事件以在窗口大小变化时更新高度。在 beforeDestroy
钩子函数中,移除了监听器,以防止内存泄漏。
在 updateHeight
方法中,使用 this.$el.querySelector()
方法获取了两个 <div>
元素,并计算它们的最大高度。然后,将最大高度赋值给 maxHeight
属性。
通过以上代码,两个独立的 <div>
元素的高度将会保持一致,并随着窗口大小的改变而更新。