【vue杂谈】判断设备是移动端还是pc端

3,135 阅读2分钟

小知识,大挑战!本文正在参与“  程序员必备小知识  ”创作活动

本文同时参与 「掘力星计划」  ,赢取创作大礼包,挑战创作激励金

前言

佛祖保佑, 永无bug。Hello 大家好!我是海的对岸!

有时我们在项目中会有支持 pc手机端需求。并且pc与手机端是两个不一样的页面。这时就要求判断设置,根据不同的设置跳转不同的路由。

直接上代码

直接上代码

//在 router/index.js 中有两个页面。
export default new Router({
    mode: 'history',
    routes: [
    {
        path: '',
        redirect: '/pc_index'
    },
    {
        path: "/pc_index", // pc端首页
        name: PcIndex,
        component: PcIndex
    },
    {
        path: '/m_index', // 手机端首页
        name: MIndex,
        component: MIndex
    }
    ]
});

App.vuemounted 方法中对设置进行判断,如下:

// APP.vue
...
data() {
    return {
        isPC: false, // true: pc设备, false: 移动设备
    };
},
mounted() {
    let isPC = localStorage.getItem('isPC');
    console.log(isPC);
    // 只有 isPC 为 null, undefined, 0 的时候, !isPC 才为true
    // typeof isPC!=“undefined” 排除了undefined
    // exp!=0 排除了数字零和 false。
    // 这里是判断 isPC是否是null
    if(!isPC && typeof isPC!="undefined" && isPC!=0){
        if(!this.firstLoad){
            if (this._isMobile()) {
                console.log("手机端");
                this.isPC = false;
                this.$router.push({ path: '/m_index'});
            } else {
                console.log("pc端");
                this.isPC = true;this.$router.push({ path: '/pc_index'});
            }
            localStorage.setItem('isPC', this.isPC);
        }
    }
},
...

其中 _isMobile() 方法如下:

// App.vue
// 正则表达式判断设备的格式,可以判断市面上大部分设备,我这里只对 pc端 和 移动端 做了处理,写在了mounted上
_isMobile() {
     let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
     return flag;
}

效果如下

chrome 浏览器pc 模式下刷新,显示如下:

20190313181232676.png

chrome 浏览器mobile 模式下刷新,显示如下:

20190313181302211.png

扫尾

这个时候会报一个不影响功能的错

Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/pc_index".

意思是 Vue重复点击相同的路由造成的

干掉的方法如下:

// router/index.js 中  加入以下代码即可

import VueRouter from "vue-router";

/**
* 处理刷新当前页面的时候,会报一个不影响功能的错
* Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location

*/

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err);
};
...