Drücke „Enter”, um zum Inhalt zu springen.

Display different Vuejs components in mobile browsers

Quelle:
https://stackoverflow.com/questions/48515023/display-different-vuejs-components-for-mobile-browsers/51053611#51053611

Let’s suppose that I have the Main.vue and the MainMobile.vue. I will add an Init.vue that will redirect. So my router/index.js is that:

import Router from 'vue-router'
import Vue from 'vue'
import Main from '@/components/Main'
import MainMobile from '@/components/MainMobile'
import Init from '@/components/Init'

Vue.use(Router)

export default new Router({
  routes: [
     {
        path: '/',
        name: 'Root',
        component: Init
     },
    {
      path: '/Main',
      name: 'Main',
      component: Main
    },
    {
      path: '/MainMobile',
      name: 'MainMobile',
      component: MainMobile
    },
  ]
})

At the Init.vue file, the mobile/desktop detection will happen:

<template>
</template>
<script>
    export default {
        name: 'Init',
        methods: {
            isMobile() {
                if( screen.width <= 760 ) {
                    return true;
                }
                else {
                    return false;
                }
            }
        },
        created() {
            if (this.isMobile()) {
                this.$router.push('/MainMobile');
            }
            else {
                this.$router.push('/Main');
            }
        }
    }
</script>
<style scoped>
</style>

The isMobile() function used is very simple, you can change to any other.

Schreibe einen Kommentar