Search code examples
vue.jswindowwidthscreenreactive-programming

Set reactive screen width with vuejs


Is it possible to have a reactive window width where a variable or data property tracks a window resize

e.g

computed:{
    smallScreen(){
        if(window.innerWidth < 720){
            this.$set(this.screen_size, "width", window.innerWidth)
            return true
        }
    return false
}

Solution

  • I don't think there's a way to do that unless you attach a listener on the window. You can add a property windowWidth on the component's data and attach the resize listener that modifies the value when the component is mounted.

    Try something like this:

    <template>
        <p>Resize me! Current width is: {{ windowWidth }}</p>
    </template
    
    <script>
        export default {
            data() {
                return {
                    windowWidth: window.innerWidth
                }
            },
            mounted() {
                window.onresize = () => {
                    this.windowWidth = window.innerWidth
                }
            }
        }
    </script>
    

    Hope that helps!