vue 可自主适配rem

看别人都是用 阿里的postcss-px2rem,缺点是把所有px转成rem,自己摸索改一下

思路:

  1. vue.config中导入全局的css(计算方式)

  1. 在vuex中添加根目录的字体大小

  1. 在main.js或者在app.vue中 添加页面大小监听

  1. vue2可以直接复制,vue3+vite 改的是 vite.config; vuex可换成pinia

  1. 示例

main.js

window.addEventListener('resize', (e) => {
    store.dispatch("updatedHtmlSize")
});

vuex

actions: {
        updatedHtmlSize() {
            let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
            let htmlDom = document.getElementsByTagName('html')[0];
            htmlDom.style.fontSize = htmlWidth / 100 + 'px';
        },
}

vue.config.js

module.exports = defineConfig({
    transpileDependencies: true,
    productionSourceMap: false,
    css: {
        loaderOptions: {
            scss: {
                additionalData: `@import "~@/assets/css/init.scss";`
            }
        }
    }
})

或者在 vite.config.js

export default defineConfig({
    css: {
        preprocessorOptions: {
            scss: {
                additionalData: `@import "@/assets/css/init.scss";`,
            },
        },
    },
    server: {
        // 开启热更新
        hmr: true,
        // 配置端口
        port: 8080,
        // 是否显示本机地址
        host: true,
        // 自动打开浏览器
        open: true,
        // 通过配置开发时,代理服务器,在开发时进行跨域解决
        // proxy: {
        //     "/api": {
        //         target: "https://api.iynn.cn/film",
        //         // 改变请求头源地址
        //         changeOrigin: true,
        //         // 重写,如果目标地址中存在 /api,就将 /api 替换为空字符串
        //         // rewrite: path => path.replace(/^\/api/, '')
        //         // rewrite: path => { }
        //     },
        // },
    },
});

init.scss(存放公共css样式)

@function px2rem($px) {
    $rem: 19.2;    // 1920 / 100
    @return (calc($px / $rem))+rem;
}

使用

.class{
    font-size: px2rem(17); // 需要适配rem
    height:200px;          // 不需要适配rem
}

或者不使用vuex或pinia,直接在main.js或app中直接监听

window.addEventListener('resize', (e) => {
    updatedHtmlSize()
});

function updatedHtmlSize() {
    let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
    let htmlDom = document.getElementsByTagName("html")[0];
    htmlDom.style.fontSize = htmlWidth / 100 + "px";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值