nuxt 手机检测,依据媒介不同,页面显示不同样式
概述
作为前端,经常会遇到某些人需要页面响应式布局,比如在pc端显示4列,在手机端要显示2列。这时候,就可以使用此方法进行处理。
/libs/deviceType.js
/**
*
* @param {*} UA ,就是userAgent
* @returns type: 设备类型
* env: 访问环境(微信/微博/qq)
*/
function isMoible(UA) {
return /(Android|webOS|iPhone|iPod|tablet|BlackBerry|Mobile)/i.test(UA)
? true
: false;
}
export function deviceType(UA) {
if (isMoible(UA)) {
return true
} else {
return false
}
}
/middleware/device.js
import { deviceType } from "~/libs/deviceType";
export default function(context) {
context.userAgent = process.server
? context.req.headers["user-agent"]
: navigator.userAgent;
// 给全局上下文添加一个属性来保存我们返回的匹配信息
context.deviceType = deviceType(context.userAgent);
// 这里注入到store,是因为我部分页面需要判断机型设置不同的样式
context.store.commit("setDeviceType", context.deviceType);
}
vuex内
state:{
deviceType:'',//设备类型
}
mutations:{
setDeviceType(state, n) {
state.deviceType=n
}
}
nuxt.config.js
export default {
css:{},
build:{},
其他属性...
router: {
middleware: ["device"],
},
}
页面使用
computed: {
isMobile() {
return this.$store.state.deviceType
},
},
mounted(){
if(this.isMobile){
console.log('手机端')
}
}