當(dāng)接到可視化大屏需求時,你是否會有以下疑問??如何做一款定制化的數(shù)據(jù)大屏? 開發(fā)可視化數(shù)據(jù)大屏如何做自適應(yīng)? vm vh、rem、scale 到底哪種比較好? 時間不夠,有沒有偷懶的方法?
實現(xiàn)方法:
css 方案 - sass
utils.scss
// 使用 scss 的 math 函數(shù),https://sass-lang.com/documentation/breaking-changes/slash-div
@use "sass:math";
// 默認(rèn)設(shè)計稿的寬度
$designWidth: 1920;
// 默認(rèn)設(shè)計稿的高度
$designHeight: 1080;
// px 轉(zhuǎn)為 vw 的函數(shù)
@function vw($px) {
@return math.div($px, $designWidth) * 100vw;
}
// px 轉(zhuǎn)為 vh 的函數(shù)
@function vh($px) {
@return math.div($px, $designHeight) * 100vh;
}
路徑配置只需在vue.config.js里配置一下utils.scss的路徑,就可以全局使用了
vue.config.js
module.exports = {
css: {
loaderOptions: {
scss: {
prependData: `@import "@/assets/css/utils.scss";`
}
}
},
}
//如果node版本比較高的話,api有會有變化
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
css: {
loaderOptions: {
scss: {
additionalData: `@import "@/scss/utils.scss";`
}
}
}
})
在 .vue 中使用
<template>
<div class="box">
</div>
</template>
<script>
export default{
name: "Box",
}
</script>
<style lang="scss" scoped="scoped">
/*
直接使用 vw 和 vh 函數(shù),將像素值傳進(jìn)去,得到的就是具體的 vw vh 單位
*/
.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>
css 方案 - less
utils.less
@charset "utf-8";
// 默認(rèn)設(shè)計稿的寬度
@designWidth: 1920;
// 默認(rèn)設(shè)計稿的高度
@designHeight: 1080;
.px2vw(@name, @px) {
@{name}: (@px / @designWidth) * 100vw;
}
.px2vh(@name, @px) {
@{name}: (@px / @designHeight) * 100vh;
}
.px2font(@px) {
font-size: (@px / @designWidth) * 100vw;
}
路徑配置在vue.config.js里配置一下utils.less
<style lang="less" scoped="scoped">
/*
直接使用 vw 和 vh 函數(shù),將像素值傳進(jìn)去,得到的就是具體的 vw vh單位
*/
.box{
.px2vw(width, 300);
.px2vh(height, 100);
.px2font(16);
.px2vw(margin-left, 300);
.px2vh(margin-top, 100);
background-color: black;
}
</style>
定義 js 樣式處理函數(shù)
// 定義設(shè)計稿的寬高
const designWidth = 1920;
const designHeight = 1080;
// px轉(zhuǎn)vw
export const px2vw = (_px) => {
return (_px * 100.0) / designWidth + 'vw';
};
export const px2vh = (_px) => {
return (_px * 100.0) / designHeight + 'vh';
};
export const px2font = (_px) => {
return (_px * 100.0) / designWidth + 'vw';
};