[Vuejs]-Add class to body before page loads

0đź‘Ť

âś…

Try having the initial styling of the app get to display: none; Then have a conditional which reacts to whether it is being loaded on desktop or mobile? That way either one will have to be selected first from an inital blank page. However, if it is taking a few seconds to load it seems there may be some issues with how the code is structured, care to post it?

0đź‘Ť

Are you using Vue Router? If so you can make the calculation of whether it is pc or mobile in the router functionality. Most likely you’ll want to put the calculation in a “beforeEach()” function in your router, or if it’s just a page or two you could put it in a “beforeRouteEnter()” function on the individual pages.

0đź‘Ť

Thanks A.Broderick for your help

Here’s how it works for me:

  1. HTML:

    <html>
      ....
    <style>
      .noDisplay {
        display: none;
      }
    </style>
      </head>
      <body class="noDisplay">
       ....
     </body>
    
  2. App.vue:

      <script>
      // 3rd party
      var MobileDetect = require('mobile-detect')
    
      // Shell
      import DesktopShell from './components/layout/desktop/d_shell.vue'
      import MobileShell from './components/layout/mobile/m_shell.vue'
    
      export default {
         name: 'app',
         data() {
         return {
         windowWidth: 0,
         windowHeight: 0,
         goMobile: this.IsMobile()
         }
    },
    components: {
      appDesktopShell: DesktopShell,
      appMobileShell: MobileShell
    },
    methods: {
      IsMobile: function () {
        if (navigator.userAgent.match(/Android/i)
          || navigator.userAgent.match(/webOS/i)
          || navigator.userAgent.match(/iPhone/i)
          || navigator.userAgent.match(/iPad/i)
          || navigator.userAgent.match(/iPod/i)
          || navigator.userAgent.match(/BlackBerry/i)
          || navigator.userAgent.match(/Windows Phone/i)
        ) {
          this.goMobile = true;
          document.body.className += ' ' + 'is-mobile';
          document.querySelector('body').classList.remove('noDisplay');
          return true;
        }
        else {
          this.goMobile = false;
          document.querySelector('body').classList.remove('noDisplay');
          return false;
        }
      },
    },
    mounted() {
      this.$nextTick(() => {
        window.addEventListener('load', () => {
          this.windowWidth = window.outerWidth
          this.windowHeight = window.outerHeight
        });
        window.addEventListener('resize', () => {
          this.windowWidth = window.outerWidth
          this.windowHeight = window.outerHeight
        });
      })
    },
    

    }

Leave a comment