实现思路
假设设计稿尺寸为 1920*1080
即:
网页宽度=1920px
网页高度=1080px
我们都知道
网页宽度=100vw
网页宽度=100vh
所以,在 1920px*1080px 的屏幕分辨率下
1920px = 100vw
1080px = 100vh
以一个宽 100px 和 100px 的 div 来说,其所占的宽高,以 vw 和 vh 为单位,计算方式如下:
vwDiv = (100px / 1920px ) * 100vw
vhDiv = (100px / 1080px ) * 100vh
css 方案 – sass
// 默认设计稿的宽度
$designWidth: 1920;
// 默认设计稿的高度
$designHeight: 1080;
// px 转为 vw 的函数
@function vw($px) {
@return calc($px / $designWidth) * 100vw;
}
// px 转为 vh 的函数
@function vh($px) {
@return calc($px / $designHeight) * 100vh;
}
vue.config.js
const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
publicPath: "",
configureWebpack: {
name: "app name",
resolve: {
alias: {
"@": resolve("src"),
},
},
},
css: {
// 全局配置 utils.scs
loaderOptions: {
sass: {
prependData: `@import "@/styles/utils.scss";`,
},
},
},
};
在 .vue 中使用
<template>
<div class="flex-box">
</div>
</template>
<script>
export default{
name: "FlexBox",
}
</script>
<style lang="scss" scoped="scoped">
.box{
width: vw(300);
height: vh(100);
font-size: vh(16);
background-color: black;
margin-left: vw(10);
margin-top: vh(10);
border: vh(2) solid red;
}
</style>
图表字体、间距、位移等尺寸自适应
1.编写工具函数
// Echarts图表字体、间距自适应
export const fitChartSize = (size, defalteWidth = 1920) => {
let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (!clientWidth) return size;
let scale = (clientWidth / defalteWidth);
return Number((size*scale).toFixed(3));
}
2.将函数挂载到原型上
import { fitChartSize } from '@src/utils/chart.js'
Vue.prototype.fitChartSize = fitChartSize;
3.在.vue
文件中直接使用this.fitChartSize()
调用