• Home (current)
    • About
    • Contact
    • Cookie
    • Home (current)
    • About
    • Contact
    • Cookie
    • Disclaimer
    • Privacy
    • TOS
    Login Or Sign up

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

    32.5k Views Asked by Will Moore At 21 March 2018 at 19:05 2025-10-19T08:42:05.841000

    <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.

    javascript vue.js skel
    Original Q&A
    3

    There are 3 best solutions below

    1
    Taki Taki On 21 March 2018 at 19:19 BEST ANSWER

    Check this library : https://github.com/apertureless/vue-breakpoints

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

    or simply go with media queries (https://www.w3schools.com/css/css3_mediaqueries_ex.asp)

    CSS :

    @media screen and (max-width: 600px) {
        #app ul il:first-of-type {
            visibility: visible;
        }
        #app ul il:last-of-type {
            visibility: hidden;
        }
    }
    
    
    @media screen and (max-width: 992px) {
        #app ul il:first-of-type {
            visibility: hidden;
        }
        #app ul il:last-of-type {
            visibility: visible;
        }
    }
    

    ofcourse it's up to you to decide what to show and what to hide on what breakpoint , i hope this helps.

    1
    Bhojendra Rauniyar Bhojendra Rauniyar On 21 March 2018 at 19:14

    You can use onorientationchange event like the following:

    methods: {
       detectOrientationChange() {
          switch(window.orientation) {  
             case -90 || 90:
                // landscape
                this.mobile = false;
                break; 
             default:
                // portrait
                this.mobile = true;
                break; 
          }
       }
    },
    mounted() {
       this.$nextTick(() => {
          window.addEventListener('onorientationchange', this.detectOrientationChange)
       }
    },
    created() {
       this.detectOrientationChange(); // when instance is created
    }
    

    Note: As the event has been deprecated, it can only be used with mobile browsers as of writing this.


    To detect screen orientation on current browsers check this post.

    0
    user11809641 user11809641 On 22 September 2020 at 08:00

    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>
    

    Related Questions in JAVASCRIPT

    • Using Puppeteer to scrape a public API only when the data changes
    • inline SVG text (js)
    • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
    • Storing the preferred font-size in localStorage
    • Simple movie API request not showing up in the console log
    • Authenticate Flask rest API
    • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
    • How to request administrator rights?
    • mp4 embedded videos within github pages website not loading
    • Scrimba tutorial was working, suddenly stopped even trying the default
    • In Datatables, start value resets to 0, when column sorting
    • How do I link two models in mongoose?
    • parameter values only being sent to certain columns in google sheet?
    • Run main several times of wasm in browser
    • Variable inside a Variable, not updating

    Related Questions in VUE.JS

    • Problems with matter.js and i18n in vue.js
    • Form Validation not working in custom component Vue
    • Authenticating vue app on each route change
    • Vue/TailwindCSS - Content is behind Sidebar
    • Vue3 Suspense Parent > Child Animation
    • Pass dynamic object data via nuxt-link to component
    • Failed to resolve import, but the path is valid, and detected as such by VSCode
    • how to use less variables in vue components?
    • Prevent a webpage from navigating away
    • Creating a modal window in product edit page in Shopware6 and saving data to custom table(repository) from a form within the modal window
    • How do I fix (or ignore) a TypeScript error that's inside a HTML template?
    • Vue.js Checkbox Alignment Issue: Centering Checkboxes Within Table Cells
    • How to reset vue product filter?
    • Vue display output of two dimensional array
    • vue js error when adding bonus items to another item

    Related Questions in SKEL

    • i get this error in console skel is not defined at main.js
    • How do I solve a skel is not defined at skel-layers-min.js django framework error
    • Dropdown symbol doesn't appear in Chrome
    • How to change vue.js data value when screen size changes?
    • W3C HTML validation error: "The text content of element script was not in the required format"
    • How to use skel.js with a prefix for the static files?
    • Skel import in Meteor Project
    • Using ske.min.js in Meteor js project
    • Skel js called in head does not always load in sharepoint 2013 master page
    • offset columns in a skel grid
    • Margin between rows with Skel
    • Loading CSS too slow using Javascript
    • Rails pixelarity template (skel)
    • Auto start/play HTML5 video using javascript to avoid use of autoplay attribute
    • Skel: Off-canvas navigation doesn't show up in mark-up and sub-naviagation appears too high

    Trending Questions

    • UIImageView Frame Doesn't Reflect Constraints
    • Is it possible to use adb commands to click on a view by finding its ID?
    • How to create a new web character symbol recognizable by html/javascript?
    • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
    • Heap Gives Page Fault
    • Connect ffmpeg to Visual Studio 2008
    • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
    • How to avoid default initialization of objects in std::vector?
    • second argument of the command line arguments in a format other than char** argv or char* argv[]
    • How to improve efficiency of algorithm which generates next lexicographic permutation?
    • Navigating to the another actvity app getting crash in android
    • How to read the particular message format in android and store in sqlite database?
    • Resetting inventory status after order is cancelled
    • Efficiently compute powers of X in SSE/AVX
    • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

    Popular # Hahtags

    javascript python java c# php android html jquery c++ css ios sql mysql r reactjs node.js arrays c asp.net json

    Popular Questions

    • How do I undo the most recent local commits in Git?
    • How can I remove a specific item from an array in JavaScript?
    • How do I delete a Git branch locally and remotely?
    • Find all files containing a specific text (string) on Linux?
    • How do I revert a Git repository to a previous commit?
    • How do I create an HTML button that acts like a link?
    • How do I check out a remote Git branch?
    • How do I force "git pull" to overwrite local files?
    • How do I list all files of a directory?
    • How to check whether a string contains a substring in JavaScript?
    • How do I redirect to another webpage?
    • How can I iterate over rows in a Pandas DataFrame?
    • How do I convert a String to an int in Java?
    • Does Python have a string 'contains' substring method?
    • How do I check if a string contains a specific word?
    .

    Copyright © 2021 Jogjafile Inc.

    • Disclaimer
    • Privacy
    • TOS
    • Homegardensmart
    • Math
    • Aftereffectstemplates