vue中判断设备切换PC或移动端

utils里面的tool.js,用于判断设备

export const isPhone = () => {
  const flag = navigator.userAgent.match( // match方法可在字符串内检索指定的值,
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  )
  if (flag) {
    return false
  } else {
    return true
  }
}

在router里面引入tool.js,进行切换

router.beforeEach((to, from, next) => { // 判断设备切换PC或移动端
  if (isPhone()) {
    const routerpc = router.options.routes.filter(v => v.name === 'Pc')[0].children // 过滤出m_index下的路由
    let add = '' // 定义即将跳转的path地址
    routerpc.filter((item) => { // 遍历刚才取出来路由组routers
      if (item.name === to.path.split('/')[1]) { // 判断 item在“_”分割后的值 和 即将跳转的path在"_" 分割后的值 是否有相同,这一步判断要求 在设置路由时,尽量保持和 格式名称一致,eg:"p_home" / "m_home"
        add = item.path
      }
    })
    if (add) {
      next()
    } else {
      next('/Pc')
    }
  } else {
    const routersphone = router.options.routes.filter(v => v.name === 'Phone')[0].children // 过滤出m_index下的路由
    let res = '' // 定义即将跳转的path地址
    routersphone.filter((item) => { // 遍历刚才取出来路由组routers
      if (item.name === to.path.split('/')[1]) { // 判断 item在“_”分割后的值 和 即将跳转的path在"_" 分割后的值 是否有相同,这一步判断要求 在设置路由时,尽量保持和 格式名称一致,eg:"p_home" / "m_home"
        res = item.path
      }
    })
    if (res) {
      next()
    } else {
      next('/Phone')
    }
  }
})

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,可以得知在Vue2,可以通过动态组件和$store.state.device来控制当前展示的页面为pc端还是移动端。同时,为了适应移动端设备的屏幕大小不一,可以使用postcss-px-to-viewport将项目的px单位转换为vw。 下面是一个简单的例子,演示如何在Vue2实现pc端移动端切换,并使用postcss-px-to-viewport将px单位转换为vw: 1.在index.vue定义pc.vue和m.vue组件,并使用动态组件和$store.state.device来控制当前展示的页面为pc端还是移动端: ```html <template> <div> <component :is="device === 'pc' ? 'pc' : 'm'"></component> </div> </template> <script> import pc from './pc.vue' import m from './m.vue' export default { components: { pc, m }, computed: { device() { return this.$store.state.device } } } </script> ``` 2.在postcss.config.js配置postcss-px-to-viewport插件,将px单位转换为vw: ```javascript module.exports = { plugins: { 'postcss-px-to-viewport': { viewportWidth: 750, // 设计稿宽度 unitPrecision: 3, // 转换后保留的小数位数 viewportUnit: 'vw', // 转换后的单位 selectorBlackList: ['.ignore', '.hairlines'], // 不转换的类名 minPixelValue: 1, // 小于等于1px的不转换 mediaQuery: false // 允许在媒体查询转换px } } } ``` 3.在组件使用vw单位代替px单位: ```html <template> <div class="container"> <div class="box"></div> </div> </template> <style scoped> .container { width: 100vw; height: 100vw; } .box { width: 100px; height: 100px; background-color: red; } </style> ``` 以上是一个简单的例子,演示了如何在Vue2实现pc端移动端切换,并使用postcss-px-to-viewport将px单位转换为vw。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值