vue项目移动端适配的两种方案

vue项目移动端适配的两种方案

方法1

1.npm install amfe-flexible --save   自适应不同屏幕
//在main.js导入amfe-flexible
import "amfe-flexible" // 解决各个页面尺寸适配性

2.npm install postcss-pxtorem --save  将px转为rem
//然后在根目录新建.postcssrc.js文件
module.exports = {
  // autoprefixer postcss其中的一个工具,获取浏览器支持的css样式,不支持加前缀
  // 脚手架已经默认集成autoprefixer这个工具,所以报错
  plugins: {
    //   'autoprefixer': {
    //   browsers: ['Android >= 4.0', 'iOS >= 8', 'ie >= 10']
    //   },
    'postcss-pxtorem': { 
      // 设计稿的1/10 vans组件的设计稿正好是375 37.5
      // 包含vant关键字,代表处理的是vant样式
      // 不包含代表处理的就不是vant样式
      rootValue(res) {
        return res.file.indexOf('vant') !==-1 ? 37.5 : 75
      },
      propList: ['*'],// 代表转换css的所有属性,*表示通用
      exclude: 'github-markdown' //忽略的选择器
    }
  }
}

方法2

1.src/utils/flexible.js文件
// rem计算方式:设计图尺寸px / 100 = 实际rem  例: 100px = 1rem
!(function(window) {
  /* 设计图文档宽度 */
  const docWidth = 750
  const doc = window.document
  const docEl = doc.documentElement
  const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
  const recalc = (function refreshRem() {
    const clientWidth = docEl.getBoundingClientRect().width
    /* 8.55:小于320px不再缩小,11.2:大于420px不再放大 */
    docEl.style.fontSize = Math.max(Math.min(20 * (clientWidth / docWidth), 11.2), 8.55) * 5 + 'px'
    return refreshRem
  })()
  /* 添加倍屏标识,安卓倍屏为1 */
  docEl.setAttribute('data-dpr', window.navigator.appVersion.match(/iphone/gi) ? window.devicePixelRatio : 1)
  if (/iP(hone|od|ad)/.test(window.navigator.userAgent)) {
    /* 添加IOS标识 */
    doc.documentElement.classList.add('ios')
    /* IOS8以上给html添加hairline样式,以便特殊处理 */
    if (parseInt(window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/)[1], 10) >= 8) { doc.documentElement.classList.add('hairline') }
  }
  if (!doc.addEventListener) return
  window.addEventListener(resizeEvt, recalc, false)
  doc.addEventListener('DOMContentLoaded', recalc, false)
}(window))

//在main.js引入
import '@/utils/flexible.js' 
2.npm install postcss-px2rem --save
配置文件同上

你可能感兴趣的:(vue.js,javascript,前端)