Search code examples
javascriptvuejs2media-queriesmatchmedia

Computed property with matchMedia function Vue.js


I have some problem with the matchMedia function that I wrote inside my computed property in Vue. The problem is when I load/refresh page, the function does not work. It only back to work after I resize the screen in Responsive Design Mode at the browser.

Here the code of my app.js

     computed: {
        widthChange() {
            if (matchMedia) {
                    var mqT = window.matchMedia(" (max-width: 850px) and (min-width: 600px) ")

                    function changeWidthT(mqT) {
                    const sectionRight = document.querySelector(".section-right")
                    if (mqT.matches) {
                        sectionRight.classList.remove("col-7")
                    }
                    else {
                        sectionRight.classList.add("col-7")
                    }
                }

                mqT.addListener(changeWidthT)
            }
        }
    },

and I call the computed property inside the parent of the page

<div class="frontpage-parent" :class="widthChange">...
</div>

Solution

  • Have you tried calling widthChange() in the mounted hook so that it runs on load?

    Edit Try placing const tst = this.widthChange; in the mousnted hook