前言:
公司内部代码分为web与mobile端,但是使用了同一个组件,导致,需要进行差异化的代码逻辑处理,所以需要我们判断平台。
方案:
第一种方法:通过navigator.userAgent检索关键词来判断用户的设备,在发现有符合关键词的就添加进入数组,最后只需要判断其长度是否为0即可
const isMobile = () => {
let userAgentInfo = navigator.userAgent;
// 移动设备平台关键词
let mobileKeywords = [
'Android',
'iPhone',
'SymbianOS',
'Windows Phone',
'iPad',
'iPod',
];
let getArr = mobileKeywords.filter(i => userAgentInfo.includes(i));
return getArr.length ? true : false;
};
第二种方法:我们知道在vue中,我们可以给vue实例绑定一个属性,那么只需要在web与mobile中各自的app.js绑定同一个属性,并且将其属性值设置为布尔值,那么我们需要在公共组件中通过getCurrentInstance去访问这个属性即可判断了
// 在web项目的app.js中
app.config.globalProperties.$isMobile = false;
// 在mobile项目的app.js中
app.config.globalProperties.$isMobile = true;
// 在公共组件中使用
import { getCurrentInstance } from 'vue';
const isMobile = getCurrentInstance().appContext.config.globalProperties.$isMobile;
结语:
方法有多种,但是最优的解决方法却需要斟酌了。