在 Vue 3 项目中进行移动端适配,设计稿宽度为 750px,设计稿标题字体大小为 28px,开发时直接在 CSS 中编写 .title { font-size: 28px; }
。以下是详细的步骤和代码示例:
1. 安装依赖
安装 postcss-pxtorem
插件,用于将像素单位转换为 rem
单位,以实现响应式设计。
npm install postcss-pxtorem --save-dev
2. 配置 postcss.config.js
在项目根目录下创建或编辑 postcss.config.js
文件,配置 postcss-pxtorem
插件。
// postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 75, // 设计稿宽度为750px,1rem = 75px
propList: ['font-size', 'width', 'height', 'padding', 'margin'], // 需要转换的属性列表
},
},
};
3. 动态设置根元素字体大小
在 main.js
中添加以下代码,根据设备宽度动态设置根元素的字体大小。
// main.js
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// 动态设置根元素字体大小
function setRootFontSize() {
const designWidth = 750; // 设计稿宽度
const root = document.documentElement;
const width = root.clientWidth;
const scale = width / designWidth;
root.style.fontSize = `${28 * scale}px`; // 设计稿标题字体大小为28px
}
setRootFontSize();
window.addEventListener('resize', setRootFontSize);
app.mount('#app');
4. 示例组件
以下是一个简单的 Vue 组件示例,展示如何使用适配后的样式。
<template>
<div class="container">
<h1 class="title">标题</h1>
<p class="content">内容</p>
</div>
</template>
<style>
.container {
width: 100%;
padding: 20px;
box-sizing: border-box;
}
.title {
font-size: 28px; /* 设计稿标题字体大小 */
margin-bottom: 10px;
}
.content {
font-size: 16px; /* 根据设计稿比例调整 */
line-height: 1.5;
}
</style>
<script>
export default {
name: 'App'
};
</script>
5. 运行项目
确保项目配置正确后,运行项目并查看效果。
npm run serve
通过以上步骤,你可以在 Vue 3 项目中实现移动端的适配,确保在不同尺寸的移动设备上都能有良好的浏览体验。设计稿宽度为 750px,设计稿标题字体大小为 28px,开发时直接在 CSS 中编写 .title { font-size: 28px; }
。
注意事项
- 确保在
postcss.config.js
中正确配置了postcss-pxtorem
插件,以便将其他像素单位转换为rem
单位。 - 在
main.js
中动态设置根元素字体大小,以适应不同尺寸的移动设备。 - 在组件的 CSS 中直接使用设计稿的字体大小,不需要进行任何转换。