On the mobile side, the REM + FLEX layout is usually used to achieve a perfect fit on the mobile side.
Rem is the font-size attribute of the root element (HTML).
For Flex layout, see: Flex Layout Tutorial
Of course, if you are using cube-UI, the library has a built-in adaptation solution that you can use if you are using another UI library.
We can useamfe-flexible
To implement REM writing,
Then throughpx2rem-loader
The dependency helps us automatically convert PX to REM, so that we can write px units directly when writing, without having to convert rem units.
Amfe-flexible: Can automatically modify the size of the root element (HTML) according to the width of the device to adapt to different terminals.
Px2rem-loader: converts CSS PX units into REM units, automatically calculates REM values, and makes writing more convenient.
The installation
npm install -s amfe-flexible
npm install px2rem-loader --save -dev
Copy the code
configuration
In the entry file main.js:
import 'amfe-flexible'
Copy the code
Modify meta attributes in index.html:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
Copy the code
Configure px2REm-loader in vue.config.js or in your own utility class (I did this in vue.config.js) :
Note: In vue-cli3.x, there is no vue.config.js configuration file by default. You need to create it manually in the root directory of the project.
const px2remLoader = { loader: 'px2rem-loader', options: { remUnit: 75 // Default conversion is 1rem = 75px, can be changed according to your design (design /10), if the width of the design is 1080, } // add px2remLoader function generateLoaders(loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader, px2remLoader] : [cssLoader, px2remLoader] if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } if (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) } }Copy the code
use
Once configured, it can be used directly.
By default, we add a font-size attribute to our root node (HTML), which can be adjusted to the size of the value depending on the device.
Effect display:
Manually add JS adaptation
<script> ; (function () {var designWidth = 375 var baseFontSize = 100 var maxAdaptWidth = 1024 var adaptDevice = function () { var deviceWidth = document.documentElement.clientWidth deviceWidth = deviceWidth > maxAdaptWidth ? maxAdaptWidth : deviceWidth var scale = deviceWidth / designWidth var adaptRootFontSize = baseFontSize * scale document.querySelector('html').style.fontSize = adaptRootFontSize + 'px' } var timer = 0 window.addEventListener('resize', function () { if (timer) { clearTimeout(timer) timer = 0 } timer = setTimeout(function () { adaptDevice() }, 0) }) setTimeout(adaptDevice, 0) }()) </script>Copy the code