Vue cli3 project uses rem and vw to realize adaptive method

Vue cli3 project uses rem and vw to realize two methods of self-adaptation

foreword

I have written two articles on the adaptive configuration of cli2 projects before, but most of the vue projects I encounter now are cli3 projects, so I think it is necessary to summarize the adaptive methods of cli3 projects, and I found
a good article on the Internet

installation configuration

The project built by vue-cli3 is much more streamlined than the project built by vue-cli2, and some default configurations are better and more rigorous, making development more efficient.

1. Use postcss-px2rem to adapt
1. Install flexible and postcss-px2rem (npm installation method flexible is suitable for mobile applications)
npm install lib-flexible --save
npm i postcss-px2rem --sav

flexible will automatically add labels to the page according to the screen, and dynamically control the values ​​of initial-scale, maximum-scale, minimum-scale and other attributes. At the same time, the refreshRem method is encapsulated in the flexible.js file, bound to the page monitoring event, and the font-size of the root element can be dynamically set.
postcss-px2rem will convert px to rem, and the rem unit is used to adapt to screens with different widths. The font-size value of the label is used to calculate the result, 1rem=the font-size value of the html label, which is equivalent to a unit converter.

Note: If the lib-flexible plug-in cannot be installed, you can download the lib-flexible.js file, the download address , and manually tag reference in the html file.
<meta name="viewport" content="width=device-width,initial-scale=1.0">

2, import lib-flexible

Introduce lib-flexible in the project entry file main.js

import 'lib-flexible'

Note (important): Since flexible will dynamically add tags to the page header, please be sure to delete this tag in the directory public/index.html! ! !
I see that some articles have a step to modify the flexible.js file ( by observing the code in the method, it is found that the refreshRem method is bound to the page monitoring event. The general logic is that when the page changes, it will be dynamically changed according to the page width and device dpr Set the font-size value of the root element to achieve the purpose of page adaptation )
This is the purpose of changing 540 to width. If the width / dpr > 540 is not changed, the font-size of the root element is a fixed value and cannot achieve self-adaptation Adapt to the purpose.
If you download the flexible.js file manually, you don’t need to modify this file. (I found that if it is a PC-side self-applicable manual download is recommended, if it is a mobile terminal, it is recommended to use npm, and in the js file installed by npm, the font-size setting Taking the dpr factor into consideration)
Manually download the relevant code of flexible.js:
insert image description here

Set the width of flexible.js to automatically adapt according to the screen size, modify the flexible.js file, (global search flexible.js
modified code:

function refreshRem(){
	var width = docEl.getBoundingClientRect().width;
	if (width / dpr > 540) {
	    width = width * dpr;
	}
	var rem = width / 10;
	docEl.style.fontSize = rem + 'px';
	flexible.rem = win.rem = rem;
}

3, configure postcss-px2rem

The configuration of px2rem is placed in vue.config.js in the vue-cli3 project (if you cannot find this file, you may be a newly built project and need to manually create vue.config.js in the project root directory)

module.exports = {
    css: {
        loaderOptions: {
          css: {},
          postcss: {
            plugins: [
              require('postcss-px2rem')({
                remUnit: 37.5
              })
            ]
          }
        }
    },
}

PS: What is the value of the remUnit configuration item? ? ? Usually we set this value according to the design drawing, the reason is very simple and easy to develop. If the width given by the design drawing is 750, we usually set remUnit to 75, so that when we write the style, we can directly restore the development according to the width and height marked on the design drawing 1:1.

Then why is it written as 37.5 here? ? ?

The reason why it is set to 37.5 is to refer to a third-party UI framework like mint-ui, because the third-party framework is not compatible with px2rem, and the value of remUnit is set to half of the width of the design drawing (750px here), that is, 1: 1 Restore the components of mint-ui, otherwise the style will change, for example, the button will become smaller.

Since it is set to 37.5, we must also change the value to half of the design drawing when writing the style.

2. Use vw adaptive
1. Install the required plug-ins (because some configurations of cli3 have been modified, npm libraries are correspondingly more)
npm i postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano postcss-import postcss-url --S
2. The postcss.config.js configuration in the root path is as follows
module.exports = {
  "plugins": {
    "postcss-import": {},
    "postcss-url": {},
    "postcss-aspect-ratio-mini": {},
    "postcss-write-svg": {
      utf8: false
    },
    "postcss-cssnext": {},
    "postcss-px-to-viewport": {
      viewportWidth: 750,     // (Number) The width of the viewport.
      viewportHeight: 1334,    // (Number) The height of the viewport.
      unitPrecision: 3,       // (Number) The decimal numbers to allow the REM units to grow to.
      viewportUnit: 'vw',     // (String) Expected units.
      selectorBlackList: ['.ignore', '.hairlines'],  // (Array) The selectors to ignore and leave as px.
      minPixelValue: 1,       // (Number) Set the minimum pixel value to replace.
      mediaQuery: false       // (Boolean) Allow px to be converted in media queries.
    },
    "postcss-viewport-units":{},
    "cssnano": {
      preset: "advanced",
      autoprefixer: false,
      "postcss-zindex": false
    }
  }
}
3. Start npm run serve and you will find that Cannot load preset “advanced”. Please check your configuration for errors and try again

This is the need to install a cssnano-preset-advanced plugin

npm i cssnano-preset-advanced --save-dev
4. Start again, all css px will become vw unit
5. Introduce compatibility scheme

①Introduce viewport-units-buggyfill.js and viewport-units-buggyfill.hacks.js two js https://github.com/rodneyrehm/viewport-units-buggyfill
②Call

<script>
    window.onload = function () {
        window.viewportUnitsBuggyfill.init({
            hacks: window.viewportUnitsBuggyfillHacks
        });
    }
</script>

This is the end of the vw configuration of cli3. If you still need to use px in the project, you can add the class to .ignore or .hairlines (.hairlines is generally used in elements that set border-width: 0.5px) For more content, please see the original article "How to use vw in Vue projects Achieving Mobile Adaptation ".

Guess you like

Origin blog.csdn.net/weixin_46995731/article/details/121769368