适配方案
第一步
在 index.html 中改变 viewport
html
<meta
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"
name="viewport"
/>
第二步
- 安装
bash
npm install amfe-flexible -S
npm install postcss-pxtorem -S
第三步配置
Vite 自身已经集成 PostCSS,因此无需单独创建 PostCSS 配置文件,可直接在 vite.config.js 文件中配置 css.postcss 选项。
注意
引入 postCssPxToRem
设置 postcss
js
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueDevTools from "vite-plugin-vue-devtools";
import postCssPxToRem from "postcss-pxtorem";
// https://vite.dev/config/
export default defineConfig({
plugins: [vue(), vueDevTools()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
css: {
postcss: {
plugins: [
postCssPxToRem({
rootValue: 75, // UI设计稿的宽度/10
unitPrecision: 3, // 转rem精确到小数点多少位
propList: ["*"], // 需要转换的属性 *表示所有
selectorBlackList: ["ignore"], // 不进行px转换的选择器
replace: true, // 是否直接更换属性值,而不添加备用属性
mediaQuery: false, // 是否在媒体查询的css代码中也进行转换
minPixelValue: 0, // 设置要替换的最小像素值
exclude: /node_modules/i, // 排除node_modules文件夹下的文件
}),
],
},
},
});
第四步导入
注意
在 main.js 中引入 amfe-flexible 插件:
js
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
import router from "./router";
// 引入配置
import "amfe-flexible";
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
第五步
- 组件使用
html
<template>
<div class="page">
<div class="header">{{ message }}</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const message = ref("首页");
</script>
<style lang="scss" scoped>
.page {
.header {
width: 750px;
height: 750px;
background: red;
font-size: 34px;
}
}
</style>