Vuejs itself is a framework for MVVM.

However, when listening to events on Windows, it is often powerless.

For example, window.resize

Well, I did some googling before I did that. I see everybody fretting about this problem.

Question: TODAY I also encountered a problem about Canvas adaptation. Change the canvas width as the window changes

Note: Important issues three times to solve the bugs in the framework first say the framework version version version (here used Vue 2.x, ES6)

Solution:

Solution a:

Step 1: Define a record width as an attribute in data

Data: {screenWidth: document. Body. ClientWidth / / here is to give to a default value (this is important)}Copy the code

Vue mounted reisze mounts vue mounted

        mounted () {
            const that = this
            window.onresize = () => {
                return (() => {
                    window.screenWidth = document.body.clientWidth
                    that.screenWidth = window.screenWidth
                })()
            }
        }Copy the code

Step 3: Watch listens for changes in the value of this property and passes val to this.screenWidth if it changes

        watch: {
            screenWidth (val) {
                this.screenWidth = val
            }
        }Copy the code

Step 4: Optimize the page congestion problem caused by frequent resize triggers

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) } } }Copy the code

Last step: Look at the results you want

Scheme 2:

In Vue 2.x, the mounted hook listens for resize events globally, and the bound function handles them later. It is also effective, much better than the previous method.Copy the code