因为这是2.0的脚手架跟3.0的配置有所区别,所以请3.0版本的移步这里
vue-cli3.0移动端适配
首先我们需要引入px2rem-loader这个依赖
它的作用是将你写好的px直接转换成rem,这样你可以正常的按设计稿去写px,但是实际到页面上就成了rem
首先下载px2rem-loader
npm install px2rem-loader --save
然后配置插件
然后找到文件目录下 build/utils.js
在cssloaders方法下引入px2rem-loader
const px2remLoader = {
loader: 'px2rem-loader',
options: {
remUnit: 7.5//设计稿宽度/10
}
};
//然后在generateLoaders方法中引入px2remloader
const loaders = [cssLoader, px2remLoader];//添加px2rem 插件
然后贴下完整配置
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
/*
这里是需要引入的px2rem-loader
*/
var px2remLoader = {
loader: 'px2rem-loader',
options: {
remUnit: 7.5//设计稿宽度/10
}
};
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
// const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
var loaders = [cssLoader, px2remLoader];//添加px2rem 插件
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader',
publicPath: '../../'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
然后需要在index.html中加入适配代码
<script>
fnResize()
window.onresize = function () {
fnResize()
}
function fnResize() {
var deviceWidth = document.documentElement.clientWidth || window.innerWidth;
document.documentElement.style.fontSize = (deviceWidth / 70) + 'px';//这个70可以根据实际情况修改
}
</script>