VueJs listener window. resize method example, vuejswindow. resize
Vuejs itself is a MVVM framework.
However, when listening for events on the window, it is often insufficient.
For example, this is window. resize.
Well, I did Baidu before I did it. The big guy is worried about this problem.
Problem: Today I also encountered a problem about canvas self-adaptation. Change the canvas width based on window changes.
Note: The important issue is to solve the bug in the framework three times. First, let's talk about the Framework Version (Vue 2.x and ES6 here)
Solution:
Step 1: Define in data that the width of a record is an attribute.
Data: {screenWidth: document. body. clientWidth // here is a default value (this is important )}
Step 2: Let's talk about how to mount the reisze event during vue mounted.
mounted () { const that = this window.onresize = () => { return (() => { window.screenWidth = document.body.clientWidth that.screenWidth = window.screenWidth })() } }
Step 3: watch listens for changes to the attribute value. If any changes occur, the val is passed to this. screenWidth.
watch: { screenWidth (val) { this.screenWidth = val } }
Step 4: optimize page freezing because the resize function is frequently triggered
watch: { screenWidth (val) { if (!this.timer) { this.screenWidth = val this.timer = true let that = this setTimeout(function () { // that.screenWidth = that.$store.state.canvasWidth console.log(that.screenWidth) that.init() that.timer = false }, 400) } } }
Last step: Check the result you want ~
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.