Vue3代码
APP文件中写入js代码
1、首先,通过isMobile()
函数判断用户的设备类型。该函数使用正则表达式匹配navigator.userAgent
字符串,以确定用户是在移动设备上访问网页还是在桌面设备上访问网页
2、然后,在onMounted()
钩子函数中,根据当前的路由路径来判断是否需要进行重定向。如果当前路径是根路径('/')或移动端首页路径('/mobile_index'),则会进一步检查设备类型。
3、如果是移动设备,则通过router.replace('/mobile_index')
将路由重定向到移动端首页。如果是桌面设备,则通过router.replace('/')
将路由重定向到桌面端首页。
<script setup lang="ts">
import { onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const 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;
}onMounted(() => {if (route.path === '/' || route.path === '/mobile_index') {if (_isMobile()) {router.replace('/mobile_index')} else {router.replace('/')}}
})
router中写法
import type { RouteRecordRaw } from 'vue-router'
export const staticRoutes: Array<RouteRecordRaw> = [// pc{path: '/',component: () => import('../views/pc_index.vue'),redirect: '/home',children: [{path: '/home',name: 'Home',component: () => import('../views/home/index.vue'),meta: {title: '首页',icon: 'ele-HomeFilled',},},// 公司产品{path: '/companyProducts',name: 'companyProducts',redirect: '/companyProducts/coalAR',children: [{path: '/companyProducts/coalAR',name: 'coalAR',component: () =>import('../views/companyProducts/coal/coalAR/index.vue'),}],},],},// 手机端首页{path: '/mobile_index',component: () => import('../views/mobile_index.vue'),redirect: '/mobileIndex',children: [{path: '/mobileIndex',name: 'mobileIndex',component: () => import('../views/mobile/mobileIndex.vue'),meta: {title: '首页',icon: 'ele-HomeFilled',}},// 公司产品{path: '/mobileProducts',name: 'mobileProducts',redirect: '/mobileProducts/coalAR',children: [{path: '/mobileProducts/coalAR',name: 'mobileCoalAR',component: () =>import('../views/mobile/mobileProducts/coal/coalAR/index.vue'),}]}]},
]
Vue2写法
在 App.vue 的 mounted 方法中对设置进行判断,如下:
//App.vue
mounted() {if (this._isMobile()) {alert("手机端");this.$router.replace('/m_index');} else {alert("pc端");this.$router.replace('/pc_index');}},
methods:{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;
}
}
/在 router/index.js 中有两个页面。
//在 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}]
});
参考vue2链接地址:【Vue】判断设备是移动端还是pc端_vue判断是pc端还是移动端-CSDN博客