A vue project is compatible with both pc and mobile

introduce:

The company requires that the project developed by Vue has both mobile and PC terminals, but the content displayed on the mobile terminal and the PC terminal is different, and the same component style is also different. The content displayed on the mobile terminal is less than that on the PC terminal. How did the project work?

Solution:

Write two copies of the route, one for the mobile terminal and one for the pc terminal. These two routes have the same address and different corresponding components. In the entry file of the route, it is judged whether to render the route of the PC or the route of the mobile terminal.

import Vue from 'vue';
import Router from 'vue-router';
import { routerM } from './routerM';
import { routerPC } from './routerPC';

Vue.use(Router);
// 是否为手机端
const ISMOBILE = function () {
  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;
};

// 创建路由实例
const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  fallback: false,
  // 这里判断后选择使用移动端的路由还是pc端的路由
  routes: ISMOBILE() ? routerM : routerPC,
});

export default router;

RouterM.js and routerPC.js codes under router:

// routerPC.js
import Layout from '@/layout'

export const routerPC = [
  {
    path: '/login',
    component: () => import('@/views/pc/login/index'),
    hidden: true
  },
]
// routerM.js
export const routerM = [
  {
    path: '/login',
    component: () => import('@/views/mobile/login/index.vue'),
    hidden: true
  },


]

It can be seen that two components have been written, and the file path is only the difference between pc and mobile when importing components.

expand

Similarly, when the style needs to be written twice, it can also be introduced on demand in main.js


// 是否为手机端
const 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
);


// PC端和移动端的公共样式
import '@public/css/common.less';
// 移动端引入公共样式
if (flag) {
  require('@/assets/css/mobileCommon.less');
}

Guess you like

Origin blog.csdn.net/hudabao888666/article/details/129383900