1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > vue项目PC 移动端适配方案

vue项目PC 移动端适配方案

时间:2021-10-07 20:08:04

相关推荐

vue项目PC 移动端适配方案

本方案的核心主要是采用vue-router来实现的。

首先我们需要有pc端和移动端的两种版本的vue文件,然后配置好自己的路由,下面是我的路由配置。

import Vue from "vue";import VueRouter from "vue-router";Vue.use(VueRouter);//默认路由export const routes = [{path: "/",redirect: "/home",},];//pc端的路由export const pcRoutes = [{path: "/",redirect: "/home",},{path: "/home",name: "Home",component: () =>import(/* webpackChunkName: "about" */ "../views/home/pc.vue"),},];//移动端设备路由export const mobileRoutes = [{path: "/",redirect: "/home",},{path: "/home",name: "Home",component: () =>import(/* webpackChunkName: "about" */ "../views/home/mobile.vue"),},];const createRouter = () =>new VueRouter({scrollBehavior: () => ({ y: 0 }),mode: "history",routes: routes,});const router = createRouter();// Detail see: /vuejs/vue-router/issues/1234#issuecomment-357941465export function resetRouter() {const newRouter = createRouter();router.matcher = newRouter.matcher; // reset router}export default router;

配置好路由之后我们就可以先写一个判断是否为移动端的方法,我默认放置的位置为 src/utils/index.js中,具体实现代码为:

// 判断设备是否为移动端的方法export const isMobile = () => {return /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(navigator.userAgent);};

写好工具之后,再到src目录下创建一个init.js文件用于判断机型从而添加相应的路由,具体实现代码如下。

import router from "./router";import { isMobile } from "./utils";import { pcRoutes, mobileRoutes } from "./router";// 判断当前设备的型号从而改变当前路由router.addRoute(isMobile() ? mobileRoutes[1] : pcRoutes[1]);

这里统一回答下部分小伙伴的疑问:有多个页面都需要做适配该怎么实现?

import router from "./router";import { isMobile } from "./utils";import { pcRoutes, mobileRoutes } from "./router";// 判断当前设备的型号从而改变当前路由,遍历所有路由并加入router// 注意:索引值为0的路由为默认路由(重定向路由)可以不用重复加入isMobile() ? mobileRoutes.forEach((item,index) => {if (index === 0) return;router.addRouter(item);}): pcRoutes.forEach((item,index) =>{if (index === 0) return;router.addRouter(item);})

最后在vue项目的入口文件main.js文件中引入init.js。

import "./init.js";

以上,有啥不对的还请指教,祝少掉头发。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。