适配方案

115 阅读1分钟

1.在index.html中的head中添加

<script>
  // 设置 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()
  }
</script>

2. npm install postcss-pxtorem@5.1.1 安装配置依赖,新建postcss.config.js文件

// postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {},
    'postcss-pxtorem': {
      rootValue: 100, // 根元素字体大小
      // propList: ['width', 'height']
      propList: ['*']
    }
  }
}

3.npm install --save-dev html-loader@0.5.5 安装配置loader,在vue.config.js中配置。不然在html中使用字符串模板会报错。

module.exports = {
  publicPath: './',
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.(html)$/,
          exclude: /node_modules/,
          use: {
            loader: 'html-loader',
            options: {
              minimize: true
            }
          }
        }
      ]
    }
  }
}