看别人都是用 阿里的postcss-px2rem,缺点是把所有px转成rem,自己摸索改一下
思路:
vue.config中导入全局的css(计算方式)
在vuex中添加根目录的字体大小
在main.js或者在app.vue中 添加页面大小监听
vue2可以直接复制,vue3+vite 改的是 vite.config; vuex可换成pinia
示例
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";
}