当前,在安装组件时,我触发一个事件以使当前元素的高度与当前元素的高度相同,但是,由于发送一次,该事件并不总是起作用,并且如果调整了元素的大小,它将不会再次发送。我还需要设置超时,因为有时ajax调用后componenet中的图表会更改高度。
何时更改当前元素的高度,如何发送此事件?
这是我目前正在做的:
mounted: function() {
setTimeout(function() {
this.$emit('resize', this.$el.offsetHeight);
},1000);
}
Run Code Online (Sandbox Code Playgroud)
Jan*_*zek 11
有更多基于ResizeObserver 的Vue 风格解决方案,但并非所有浏览器都支持 - 但
文档:https : //caniuse.com/#feat=resizeobserver
示例
data () {
return {
ro: null,
}
},
methods: {
onResize () {
this.$emit('resize', this.$refs.myElement.offsetHeight)
},
},
mounted () {
this.ro = new ResizeObserver(this.onResize)
.observe(this.$refs.myElement)
},
beforeDestroy () {
this.ro.unobserve(this.$refs.myElement)
}
Run Code Online (Sandbox Code Playgroud)
在 ResizeObserver 成为标准之前,您可以使用 MutationObserver 来跟踪元素的大小。代码笔链接
new Vue({
el: "#app",
data() {
return {
width: null,
height: null,
observer: null
};
},
mounted() {
//get initial dimensions. Mutation observer will observe mutations only
const box = this.$refs.box,
boxSize = box.getBoundingClientRect();
this.width = Math.trunc(boxSize.width) + "px";
this.height = Math.trunc(boxSize.height) + "px";
// initialize the observer on mount
this.initObserver();
},
//disconnect the observer before destroy
beforeDestroy() {
if (this.observer) this.observer.disconnect();
},
methods: {
initObserver() {
const box = this.$refs.box,
vm = this,
config = {
attributes: true
};
// create the observer
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// check if the mutation is attributes and update the width and height data if it is.
if (mutation.type === "attributes") {
let {
width,
height
} = box.style;
vm.width = width;
vm.height = height;
}
});
});
// observe element's specified mutations
observer.observe(box, config);
// add the observer to data so we can disconnect it later
this.observer = observer;
}
}
});Run Code Online (Sandbox Code Playgroud)
.box {
text-align: center;
font-family: Arial;
box-sizing: border-box;
width: 150px;
height: 150px;
border: 2px solid red;
padding: 10px;
margin: 0 auto;
resize: both;
overflow: auto;
}
.size {
color: #2a9966;
font-weight: 600;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<!-- more info on refs: https://vuejs.org/v2/api/#ref -->
<div class=" box" ref="box">
<h4>Resize Me</h4>
<p>
<span>width: </span><span class="size">{{ width }}</span>
</p>
<p>
<span>height: </span><span class="size">{{ height }}</span>
</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1432 次 |
| 最近记录: |