Display different Vuejs components for mobile brow

2020-01-30 07:34发布

I am developing an SPA using Vue 2.0. The components developed so far are for the "desktop" browsers, for example, I have

Main.vue, ProductList.vue, ProductDetail.vue,

I want another set of components for the mobile browsers, such as MainMobile.vue, ProductListMobile.vue, ProductDetailMobile.vue,

My question is, where and how do I make my SPA render the mobile version of components when viewing in a mobile browser?

Please note that I explicitly want to avoid making my components responsive. I want to keep two separate versions of them.

Thanks,

标签: vue.js vuejs2
8条回答
三岁会撩人
2楼-- · 2020-01-30 08:31

I had this same problem, I solved it using a neutral and no layout vue file (Init.vue) that will be accessed by mobile and desktop, and this file redirects to the correct file.

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.

查看更多
等我变得足够好
3楼-- · 2020-01-30 08:35

A bit late for this but, in case if any of you are looking to bind watchers for the viewport size, and/or check whenever the page loads. Its a lot of boilerplate to write but can be useful for small applications.

export default {
  data: () => ({
    isMobile: false
  }),

  beforeDestroy () {
    if (typeof window !== 'undefined') {
      window.removeEventListener('resize', this.onResize, { passive: true })
    }
  },

  mounted () {
    this.onResize()
    window.addEventListener('resize', this.onResize, { passive: true })
  },

  methods: {
    onResize () {
      this.isMobile = window.innerWidth < 600
    }
  }
}
查看更多
登录 后发表回答