vuecli3 实现 移动端和pc端 界面切换(两套代码)

适合场景

多页面多系统应用

所有系统都在同一目录下。配置多入口多出口。每个系统之间可以链接。每个系统内依然采用Vue单页应用开发。
产品需求:一套代码 兼容pc端和移动端 , 移动端和pc端的样式布局差别很大,需要使用多界面,并判断使用手机的时候跳转移动端代码,使用pc端跳转pc端代码。

项目目录
在这里插入图片描述

分为两部分代码,pc 和mobile

第一步:创建一个登陆页面的文件

在项目public文件夹下创建一个login.html,其实就是将index.html复制一份,将title改一下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="login"></div>

</body>

</html>

第二步:在src文件夹下创建一个modules文件夹,分别创建login.main.js、login.router.js、login.vue三个文件
在这里插入图片描述
三个文件内容如下:

login.main.js: 仿照main.js

import Vue from 'vue'
import App from './login.vue'
import router from './login.router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#login')

login.router.js (仿照router.js)

router/index.js中需要的设置

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 首页用重定向的方式来进行适配的方案:
const redirectPath = /Android |webos | iphone iPod BlackBerry liPad/i.test(navigator.userAgent) ? '/m_index' : '/index';


import index from '../../components/index.vue'
Vue.use(VueRouter)

const routes = [
 {
    path: "/",
    redirect: redirectPath,
   
  },
  {
    path: '/index',
    name: index,
    component: index
  },

]
const router = new VueRouter({
  // 去掉路由中的#号
  mode: 'history',
  routes
})
router.beforeEach((to, from, next) => {

  if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    window.location.href = '/m_index.html/'
    return
  }
  next()
})
export default router

login.router.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../../components/login.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: login,
    component: login
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

界面自行配置

vue.config.js

const path = require('path')
const debug = process.env.NODE_ENV !== 'production'
module.exports = {

  publicPath: '/', // 根域上下文目录
  outputDir: 'dist', // 构建输出目录
  assetsDir: 'static', // 静态资源目录 (js, css, img, fonts)
  lintOnSave: false, // 是否开启eslint保存检测,有效值:ture | false | 'error'
  runtimeCompiler: true, // 运行时版本是否需要编译
  transpileDependencies: [], // 默认babel-loader忽略mode_modules,这里可增加例外的依赖包名
  productionSourceMap: true, // 是否在构建生产包时生成 sourceMap 文件,false将提高构建速度
  configureWebpack: config => { // webpack配置,值位对象时会合并配置,为方法时会改写配置
    if (debug) { // 开发环境配置
      config.devtool = 'cheap-module-eval-source-map'
    } else { // 生产环境配置
    }
    Object.assign(config, { // 开发生产共同配置
      resolve: {
        // 起别名
        alias: {
          '@': path.resolve(__dirname, './src'),
          '@c': path.resolve(__dirname, './src/components'),
          'vue$': 'vue/dist/vue.esm.js',
          'assets': '@/assets',
          'common': '@/common',
          'components': '@/components',
          'network': '@/network',
          'router': '@router',
          'views': '@views',
        }
      },

    })
  },
  // css: {
  //   loaderOptions: {
  //     css: {},
  //     postcss: {
  //       plugins: [
  //         require('postcss-px2rem')({
  //           remUnit: 37.5
  //         })
  //       ]
  //     }
  //   }
  // },
  pages: {
    //(1)输出一个页面
    //  main: {
    //    entry: 'src/main.js',
    //    template: 'public/index.html',
    //    filename: 'maker.html',
    //    chunks: ['chunk-vendors', 'chunk-common', 'index']
    //  },
    //(2)输出多个页面
    login: {
      template: "public/login.html",
      entry: "src/modules/mobile/login.main.js",
      filename: "login.html",
      title: "login",
      keywords: "333",
      description: "444",
    },
    index: {
      template: "public/index.html",
      entry: "src/modules/pc/main.js",
      filename: "index.html",
      title: "index",
      keywords: "333",
      description: "444",
    }
  },
  chainWebpack: config => { // webpack链接API,用于生成和修改webapck配置,https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
    // 这里是对环境的配置,不同环境对应不同的BASE_URL,以便axios的请求地址不同
    config.plugin('define').tap(args => {
      args[0]['process.env'].BASE_URL = JSON.stringify(process.env.BASE_URL)
      return args
    })


    if (debug) {
      // 本地开发配置
    } else {
      // 生产开发配置
    }
  },
  parallel: require('os').cpus().length > 1, // 构建时开启多进程处理babel编译
  pluginOptions: { // 第三方插件配置
  },
  pwa: {
  },

  devServer: {
    open: false,
    host: 'localhost',
    port: 80,
    https: false,
    hotOnly: false,
    // 注意下面 需要写入接口 , 如果没有接口则进行注释即可
    proxy: { // 配置跨域
      '/api': {
        target: 'https://127.0.0.1:80',	//接口域名
        ws: true,	//是否代理websockets
        changOrigin: true,	//是否跨域
        pathRewrite: {		//重置路径
          '^/api': ''
        }
      }
    },
  }
}


即可完成

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
Vue 可以通过检测浏览器的 user agent(`navigator.userAgent`)来区分移动端和 PC 端。以下是一个简单的实现方法。 首先,在 Vue 组件中,可以使用通过 `mounted` 生命周期函数来监听页面的加载完成,然后访问全局的 `navigator.userAgent` 字符串: ```javascript mounted () { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { // 移动端逻辑 // 例如,在移动端监听 touchstart 事件 document.addEventListener('touchstart', this.handleTouchEvent) } else { // PC 端逻辑 // 例如,在 PC 端监听 keydown 事件 document.addEventListener('keydown', this.handleKeyDown) } } ``` 在上述代码中,我们通过正则表达式检测 `navigator.userAgent` 字符串中是否包含移动设备的关键字,例如 `"Android"`、`"iPhone"` 等。如果匹配成功,则可以判断为移动端。否则,就可以判断为 PC 端。 在移动端逻辑中,可以监听移动端的触摸事件(如 `touchstart`、`touchmove`、`touchend` 等)来实现相应的键盘事件监听。在 PC 端逻辑中,则可以监听键盘事件(如 `keydown`、`keyup` 等)。 最后,需要在组件销毁时,也就是通过 `beforeDestroy` 生命周期函数,移除事件监听器,以免造成内存泄漏: ```javascript beforeDestroy () { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { document.removeEventListener('touchstart', this.handleTouchEvent) } else { document.removeEventListener('keydown', this.handleKeyDown) } } ``` 通过以上逻辑,我们可以区分移动端和 PC 端,并实现相应的键盘事件监听。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘴巴嘟嘟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值