vue移动端自适应

本文详细介绍了如何使用Vue CLI创建项目,配置rem单位并借助postcss-pxtorem实现从px到rem的转换。通过新建vue.config.js文件,解决编译过程中的报错,并完成移动端布局的自动适应。适合前端开发者快速掌握响应式设计技巧。
摘要由CSDN通过智能技术生成

1、vue ui创建项目
在这里插入图片描述
2、选择基本配置项
在这里插入图片描述
3、运行项目
在这里插入图片描述
4、新建rem.js文件

// 基准大小
const baseSize = 32
// 设置 rem 函数
function setRem () {
  // 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
  const scale = document.documentElement.clientWidth / 750
  // 设置页面根节点字体大小
  document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置rem
window.onresize = function () {
  setRem()
}

在这里插入图片描述
5、在main.js中引入

import './utils/rem'

在这里插入图片描述
6、安装postcss-pxtorem 自动转换px为rem

npm install postcss-pxtorem -D

在这里插入图片描述
7、新建 .postcssrc.js文件

module.exports = {
  "plugins": {
    "postcss-import": {},
    "postcss-url": {},
    // to edit target browsers: use "browserslist" field in package.json
    "autoprefixer": {},
    "postcss-pxtorem": {
      "rootValue": 32,
      "propList": ["*"]
    }
  }
}

在这里插入图片描述
8、继续运行报错
在这里插入图片描述
9、新建vue.config.js文件(解决第八步报错 )

module.exports = { 
  //双击index.html文件直接运行
  publicPath: './',
  // 当运行 vue-cli-service build 时生成的生产环境构建文件的目录
  outputDir: 'dist',
  lintOnSave: true,
  // 是否使用包含运行时编译器的 Vue 构建版本。设置true后你就可以在使用template
  runtimeCompiler: true,
  // 生产环境是否生成 sourceMap 文件 sourceMap的详解请看末尾
  productionSourceMap: false,
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') { // 为生产环境修改配置...
      return {

      }
    } else {
      return {

      }
    }
  },
  css: {
    extract: true, // 开启 CSS source maps?
    sourceMap: false, // css预设器配置项
    modules: false,
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-pxtorem')({
            rootValue: 37.5, // 换算的基数
            selectorBlackList: ['weui', 'mu'], // 忽略转换正则匹配项
            propList: ['*']
          })
        ]
      }
    }
  },

  // webpack-dev-server 相关配置
  devServer: { // 设置代理
    hot: true, // 热加载
    host: '0.0.0.0', // ip地址
    port: 8082, // 端口
    https: false, // false关闭https,true为开启
    open: true, // 自动打开浏览器
    overlay: {
      warnings: false,
      errors: false
    }
  }
}

在这里插入图片描述

10、自动适配完成
在这里插入图片描述

  • 22
    点赞
  • 124
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值