当前位置:   article > 正文

vue3+vite+js 实现移动端,PC端响应式布局_vite响应式

vite响应式

目前使用的是vue3+vite,没有使用ts

纯移动端|PC端

这种适用于只适用一个端的情况
方法:amfe-flexible + postcss-pxtorem相结合
① 执行以下两个命令

npm i -S amfe-flexible
npm install postcss-pxtorem --save-dev
  • 1
  • 2

main.js文件引用

import 'amfe-flexible'
  • 1

③ 根目录新建一个postcss.config.js文件,文件内容如下:

// postcss.config.js
module.exports = {
    plugins: {
        'postcss-pxtorem': {
            rootValue({ file }) {
                return file.indexOf('vant') !== -1 ? 37.5 : 75; // 因为vant框架是以375px的稿子为基础的,rootValue 以设计稿除以10来设置
            },
            propList: ['*'], // 需要转换的css属性,默认*全部
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

到这里就安装完成了,重新运行项目就可以在浏览器看到变化了

移动端+PC端

这种可用于一套UI或两套UI适配于移动端及PC端的情况
① 新建个js文件,我放在src平级下新建utils–rem.js文件
store接入可参考这篇文章

import useUserStore from "@/store/modules/userStore.js" 
const store = useUserStore()

// 获取是否为手机端
const isMobile = () => {
  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)
  return !!flag
}
export function setRem() {
  // 获取页面的宽度
  const deviceWidth = document.documentElement.clientWidth
  // 手机端  (768可自己调整)
  if (deviceWidth<=768){
    if (store) store.setDevice('mobile')  // 我这边基本每个页面都需要用到,所以存到vuex,你们可按照自己实际项目来
    document.documentElement.style.fontSize = deviceWidth / 3.75 + 'px'  //  我这里是按照100px来的,3.75:设计稿宽度(375)/100
  } else {
  // 电脑端
    if (store) store.setDevice('pc')
    document.documentElement.style.fontSize = deviceWidth / 14.4 + 'px'
  }
}
setRem()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

② 页面调用

<template>
    <div class="title">{{store.device}}</div>
</template>
<script setup>
import { computed,onMounted} from 'vue'
import useUserStore from "@/store/modules/userStore.js"
import { setRem } from '@/utils/rem.js' // 引入文件
import { debounce } from 'throttle-debounce' // 用于防抖的

const store = useUserStore()
onMounted(() => {
  window.onresize = debounce(500, () => {
    setRem()
  }, { atBegin: false })
})
</script>
<style lang="scss" scoped>
.title{
    font-size: 0.14rem;
}
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

这里就配置完了,如果有用到组件库的需要自己去单个适配下了
我这边移动端375设计稿字体大小为14px,PC端1440设计稿字体大小为14px
在这里插入图片描述

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/751523
推荐阅读
相关标签
  

闽ICP备14008679号