VUE判断PC端与移动端,并进行跳转
最近在项目上时第一次尝试双端编写,所以学习了一下在VUE项目中进行PC与移动端判断,并实现跳转到不同组件。
第一步
在APP.vue中,对router-view进行命名,对name属性进行编写,同时增加一个showPage属性进行PC、移动端标识
<template>html
<div id="app">
<router-view v-if="showPage == 1" name="mobile"></router-view>
<router-view v-if="showPage == 2" name="pc"></router-view>
</div>
</template>
第二步
在APP.vue中利用setup语法糖,定义showPage,并进行判断
import { onMounted,ref } from 'vue';
//移动端路由为1 PC端路由为2
const showPage = ref(1)
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(_isMobile()){
//移动端
showPage.value = 1
}else{
//PC 端
showPage.value = 2
}
})
在路由文件router中,修改components,其中的pc和mobile对应router-view中的name属性
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path : '/',
name : 'index',
components : {
default : () => import('@/views/index.vue'),
pc : () => import('@/views/index.vue'),
mobile : () => import('~/components/mobile/index.vue')
}
]
const router = createRouter({
history : createWebHashHistory(),
routes
})
export default router
当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »