Vue/CLI 3.0 移动端自适应开发指南:一套代码适配多屏
Vue/CLI 3.0 移动端自适应开发指南:一套代码适配多屏
本指南将详细介绍使用 Vue/CLI 3.0 开发移动端应用时实现自适应布局的最佳实践,帮助你快速构建响应式移动端页面。
1. 配置移动端 viewport
在 index.html 的 <head> 标签中加入以下代码:
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'>
2. 安装 postcss-pxtorem
使用 postcss-pxtorem 可以将我们书写的 px 单位转换为 rem 单位,从而实现自适应。
npm install postcss-pxtorem --save-dev
3. 配置 postcss.config.js
在项目根目录下创建 postcss.config.js 文件,加入以下代码:
module.exports = {
plugins: {
'autoprefixer': {},
'postcss-pxtorem': {
rootValue: 75, // 设计稿宽度的 1/10
propList: ['*'],
selectorBlackList: ['van-'], // 不对 vant 组件样式进行转换
}
}
}
4. 配置 vue.config.js
在项目根目录下创建 vue.config.js 文件,加入以下代码:
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 75,
propList: ['*'],
selectorBlackList: ['van-'],
})
]
}
}
}
}
5. 使用 Vant 组件库
在移动端开发中,使用 Vant 组件库可以快速搭建页面,同时 Vant 也对移动端自适应进行了处理。
安装 Vant 组件库:
npm install vant -S
在 main.js 中引入 Vant:
import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
6. 设置根元素字体大小
在入口组件 App.vue 中,加入以下代码:
<style>
html {
font-size: 16px;
}
</style>
这里我们设置 html 的字体大小为 16px。
7. 编写样式
在编写样式时,使用 rem 单位代替 px 单位,同时需要注意 Vant 组件库的样式不需要进行自适应处理。
<style>
.container {
width: 7.5rem;
margin: 0 auto;
padding-top: 2rem;
background-color: #f5f5f5;
}
.title {
font-size: 0.36rem;
color: #333;
margin-bottom: 0.2rem;
text-align: center;
}
</style>
<template>
<div class='container'>
<h2 class='title'>Hello Vue</h2>
<van-button type='primary'>Primary</van-button>
</div>
</template>
以上就是一套基于 Vue/CLI 3.0 的移动端自适应代码的设计。
注意:
postcss-pxtorem的rootValue需要根据你的设计稿宽度进行调整。- 可以使用
selectorBlackList排除不需要进行自适应的元素。 - 确保你的项目中已经安装了
autoprefixer,它可以自动添加浏览器前缀。 - 使用 Vant 组件库可以简化移动端开发,并提供良好的自适应性。
- 在编写样式时,注意使用 rem 单位,并根据不同的屏幕尺寸调整元素大小。
通过以上步骤,你可以轻松实现 Vue/CLI 3.0 项目的移动端自适应,并构建出高质量的响应式移动端页面。
原文地址: https://www.cveoy.top/t/topic/l1IL 著作权归作者所有。请勿转载和采集!