Vue 中使用lib-flexiblepostcss-pxtorempx单位转化为rem单位

  1. 下载 npm i lib-flexible postcss-pxtorem
  2. 首先在main.js文件中导入lib-fiexible
    import Vue from 'vue'
    import App from './App.vue'
    import './registerServiceWorker'
    import router from './router'
    import store from './store'
    // 引入全局的样式文件
    import '@/styles/index.scss'
    // 权限验证文件
    import '@/permission'
    // 引入 flexible 用于设置 rem 基准值
    import 'lib-flexible/flexible.js'
    Vue.config.productionTip = false
    
    new Vue({
        router,
        store,
        render: (h) => h(App),
    }).$mount('#app')
    
  3. vue.config.js中配置
    module.exports = {
    	css: {
            loaderOptions: {
                postcss: {
                    plugins: [
                        require('postcss-pxtorem')({
                            // 把px单位换算成rem单位
                            rootValue: 75, // // 设计稿宽度的1/10
                            selectorBlackList: ['weui', 'mu'], // 忽略转换正则匹配项
                            propList: ['*'] // 需要做转化处理的属性,如`hight`、`width`、`margin`等,`*`表示全部
                        })
                    ]
                }
            }
        }
    }
    
  4. 也可以新建一个文件postcss.config.js
    在这里插入图片描述
    module.exports = {
        plugins: {
            autoprefixer: {},
            // flexible配置
            "postcss-pxtorem": {
                "rootValue": 75, // 设计稿宽度的1/10
                "propList": ["*"] // 需要做转化处理的属性,如`hight`、`width`、`margin`等,`*`表示全部
            }
        }
    }
    
  5. 页面
    在这里插入图片描述
    <template>
        <div class="home_box">
            首页
        </div>
    </template>
    <script>
    export default {
        
    }
    </script>
    <style lang="scss" scoped>
    .home_box {
        width: 200px;
        height: 200px;
        background-color: #ff5033;
        font-size: 16px;
    }
    </style>
    
  6. 效果,可以看到样式大小会跟随变化
    在这里插入图片描述
Logo

前往低代码交流专区

更多推荐