我相信有更好的方法可以做到这一点,但在我想出办法之前,这一种方法会对你有用:
基本上,你只需要一个数据props 和一个观察者就可以做到这一点.
new Vue({
el: '#app',
data() {
return {
windowHeight: window.innerHeight,
txt: ''
}
},
watch: {
windowHeight(newHeight, oldHeight) {
this.txt = `it changed to ${newHeight} from ${oldHeight}`;
}
},
mounted() {
this.$nextTick(() => {
window.addEventListener('resize', this.onResize);
})
},
beforeDestroy() {
window.removeEventListener('resize', this.onResize);
},
methods: {
onResize() {
this.windowHeight = window.innerHeight
}
}
});
这将输出更改
<div id="app">
<br> Window height: {{ windowHeight }} <br/>
{{ txt }}
</div>