參考文檔:element-resize-detector的github連接javascript
1.安裝element-resize-detector
npm install element-resize-detector
2.引入到script中
<script> import elementResizeDetectorMaker from "element-resize-detector"; </script>
3.在mounted中使用
mounted() { this.watchSize(); }, methods: { watchSize() { const _this = this; var erd = elementResizeDetectorMaker(); erd.listenTo(this.$refs.fan, (element) => { // 這裏的this.$refs.fan指定要監聽的元素對象,對應的是<div ref="fan"></div> var width = element.offsetWidth; var height = element.offsetHeight; _this.$nextTick(() => { // 這裏填寫監聽改變後的操做 //const element_style = _this.$refs.gif1.style; //console.log("Size: " + width + "x" + height); //if (width > height) { // element_style.height = "100%"; // element_style.width = "auto"; //} else { // element_style.height = "auto"; // element_style.width = "100%"; //} }); }); }, }