Search code examples
javascriptvue.jsenquire.js

Using Enquire.js with Vue.js to query about the browser's size


I'm using Enquire.js with Vue.js to query the browser's size and update two data properties accordingly. So, if I do this:

ready: function() {
    // Listen for changes in the browser's size
    window.addEventListener("resize",
    enquire.register("screen and (max-width:400px)", {
        match: function() {
            this.displayIsLarge = false;
            this.displayIsSmall = true;
            console.log("the screen is now small");
        },
        unmatch: function() {
            this.displayIsLarge = true;
            this.displayIsSmall = false;
            console.log("the screen is now large");
        }
    })
    );
}

It will output the correct message in the console (jsfiddle here), however it's not changing the value of displayIsLarge and displayIsSmall. What am I missing here?


Solution

  • The problem was with the scope of this. The full working code would be:

    ready: function() {
        var self = this;
        // Listen for changes in the browser's size
        window.addEventListener("resize",
        enquire.register("screen and (max-width:400px)", {
            match: function() {
                self.displayIsSmall = true;
                self.displayIsLarge = false;
                console.log("the screen is now small");
            },
            unmatch: function() {
                self.displayIsLarge = true;
                self.displayIsSmall = false;
                console.log("the screen is now large");
            }
        })
        );
    }
    

    Jsfiddle here