vue 项目 切换手机端和pc端。同一个项目,配置不同的路由

1, 首先判断设备:在main.js里面写

// vue原型挂载 - 是否PC端
if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    Vue.prototype.$pc = false
    hostConfig.vconsole && new VConsole()
} else {
    Vue.prototype.$pc = true
    let winWidth = document.documentElement.offsetWidth ||
    document.body.offsetWidth
    winWidth = winWidth < 1366 ? 1366 : winWidth
    let oHtml = document.getElementsByTagName('html')[0]
    oHtml.style.fontSize = 100 * winWidth / 1920 + 'px'
    window.addEventListener('resize', function () {
        let winWidth = document.documentElement.offsetWidth || document.body.offsetWidth
        winWidth = winWidth < 1366 ? 1366 : winWidth
        let oHtml = document.getElementsByTagName('html')[0]
        oHtml.style.fontSize = 100 * winWidth / 1920 + 'px'
    })
}

2, 在app.vue里面

watch: {
        $route: function (to, from) {
            if (to.name.indexOf('_p') > 0 && !this.$pc) {
                this.$router.replace(to.name.split('_p')[0])
            } else if (to.name.indexOf('_p') < 0 && this.$pc) {
                this.$router.replace(to.name + '_p')
            }
        }
    },

3,路由表配置

       {
            path: '/index',
            name: 'index',
            component: resolve => require(['../views/Index/index.vue'], resolve)
        },
        {
            path: '/index_p',
            name: 'index_p',
            component: resolve => require(['../views/Index_p/index.vue'], resolve)
        },

4, 打完收工

上一篇:响应式用法rem,需要加入这段JS


下一篇:js实现移动端兼容设置