How to change vue.js data value when screen size changes?

Will Moore picture Will Moore · Mar 21, 2018 · Viewed 23.6k times · Source

<div id="app">
    <ul>
        <!-- On mobile devices use short heading -->
        <template v-if="mobile == 1">
            <li><a href="#">Heading</a></li>
        </template>
        <!-- Else use long heading -->
        <template v-else-if="mobile == 0">
            <li><a href="#">Heading Long</a></li>
        </template>
    </ul>
</div>

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script>
    var app = new Vue({
            el: '#app',
            data: {
                mobile: 0
            }
});

I'm looking for a way to change the value of 'mobile' when the screen breakpoint of (max-width: 547px) becomes active. And to change it back when this mobile breakpoint becomes inactive (screen goes over 547px). I normally use skel (https://github.com/ajlkn/skel) to deal with screen breakpoints, but I cannot access skel from inside Vue, or vice-versa. I would forego using Vue for this particular task, but display: none, and display: block throws off my presentation--turning my element into a block.

Answer

user11809641 picture user11809641 · Sep 22, 2020

If you are using Vuetify, you can programmatically adjust the data value based on the built in breakpoints of xs, sm, md, lg, xl (as specified in Material Design) as follows:

computed: {
  mobile() {
    return this.$vuetify.breakpoint.sm
  },
}

mobile will change to true as soon as the screen width is less than 600px.

Your code would then be something like this (I also moved the if statement to be directly on the <li> element):

<div id="app">
    <ul>
        <!-- On mobile devices use short heading -->
        <li v-if="mobile"><a href="#">Heading</a></li>
        <!-- Else use long heading -->
        <li v-else><a href="#">Heading Long</a></li>
    </ul>
</div>