一、amfe-flexible
1. 首先把安装amfe-flexible
npm i amfe-flexible -S
2. 配置 postcss-pxtorem
postcss-pxtorem会将px转换为rem
npm install --save postcss-pxtorem@5.1.1
3. 在项目入口文件main.js 中引入amfe-flexible
import 'amfe-flexible'
4. 在根目录的index.html 的头部加入手机端适配的meta代码
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
5. Vue CLI 内部使用了 PostCSS
默认开启了autoprefixer (浏览器前缀规则)
工程化项目根路径下创建 postcss.config.js 文件
module.exports = {
module: {
rules: [{
test: /\.vue$/,
use: 'vue-loader'
}, {
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'scss-loader'
]
}, {
test: /\.css$/,
use: [
'style-loader',
'css-loader',
]
}]
},
plugins: {
'autoprefixer': {
overrideBrowserslist: [
"Android 4.1",
"iOS 7.1",
"Chrome > 31",
"ff > 31",
"ie >= 8"
]
},
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*']
}
}
}
创建vue.config.js
简单版
module.exports = {
publicPath:'./'
}
复杂版
let path = require('path')
module.exports = {
// 公共路径
publicPath: './',
// 配置webpack http 服务 devServer
devServer: {
// 在指定的dist目录开启http服务
contentBase: path.resolve(__dirname, "dist"),
// 端口
port: 8080,
// 自动打开浏览器
open: true,
// 代理服务器地址
// 数据接口地址:
// 例如:
// 原来访问: http://127.0.0.1:3000/example (数据接口地址) 本来属于跨域 /login
// 原来访问: https://baidu.com/example (数据接口地址) 本来属于跨域 /login
// 现在访问: http://127.0.0.1:8080/api/example (在项目中使用) /api/login
proxy: {
//代理api
'/api': {
// 代理接口(服务器地址)
// target: 'http://127.0.0.1:3000',
target: 'https://baidu.com',
//是否跨域
changeOrigin: true,
//重写路径
pathRewrite: {
//代理路径
'^/api': ''
}
}
}
}
}
移动端防止大屏幕字体过大 和防止微信游览器改变字体大小(rem.js)
export function initRootFontSize() {
let init = ()=> {
let w = document.documentElement.offsetWidth || window.innerWidth;
if(w >= 375)
document.documentElement.style.fontSize="37.5px";
}
window.addEventListener('resize',init);
window.addEventListener('load',init);
init();
}
export function handleFontSize() {
WeixinJSBridge.invoke('setFontSizeCallback', { fontSize: 0 })
WeixinJSBridge.on('menu:setfont', () => {
WeixinJSBridge.invoke('setFontSizeCallback', { fontSize: 0 })
})
}
if (
typeof WeixinJSBridge === 'object'
&& typeof WeixinJSBridge.invoke === 'function'
) {
handleFontSize()
} else {
document.addEventListener('WeixinJSBridgeReady', handleFontSize, false)
}
export default {
initRootFontSize,
handleFontSize
}
最终项目目录截图