使用is-mobile依赖🚀
- 前端开发中经常会遇到根据不同屏幕尺寸或不同设备动态去切换一些东西。记录一下。
- 先安装is-mobile 包
$ npm install is-mobile -D
$ yarn add is-mobile -D
"dependencies": {
"is-mobile": "^2.2.1",
}
- 在页面需要使用的地方引入即可,可以在router文件中通过路由守卫判断跳转PC页面还是h5页面
import mobile from 'is-mobile'
const route = [
{
path: '/account',
name: 'account',
component: Layout,
redirect: '/account/web/personal/personal-info'
},
{
path: '/account/web/personal/personal-info',
name: 'personalAccount',
component: () => import('@/views/account/web/personal/PersonalInfo'),
meta: {
accountInfo: true
}
}]
route.beforeEnter: (to, from, next) => {
if (store.state.account.tenantType === 'PERSON') {
mobile() ? next({ name: 'mobileAccount' }) : next()
} else {
mobile()
? next({ name: 'mobileAccount' })
: next({ name: 'companyCompanyAccount' })
}
}
正则方法判断🚀
export function hasMobile () {
let isMobile = false;
if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
isMobile = true;
}
if (document.body.clientWidth < 800) {
isMobile = true;
}
return isMobile
}
import { hasMobile } from '@/utils';
export default {
state: {
hasMobile: hasMobile(),
},
mutations: {
setMobile (state, hasMobile) {
state.hasMobile = hasMobile
},
},
}
import { hasMobile } from '@/utils'
mounted () {
window.addEventListener('resize', debounce(() => {
this.$store.commit('setMobile', hasMobile());
}));
}
css媒体查询方法🚀
@media not|only mediatype and (mediafeature and|or|not mediafeature) {
CSS-Code;
}
@media screen and (max-width: 300px) {
body {
background-color:lightblue;
}
}