vue实现移动端适配
移动端适配方案
使用Vue实现移动端适配需要结合多种技术手段,确保页面在不同尺寸设备上正常显示。以下是几种常用方法:
viewport meta标签配置
在public/index.html或模板文件中添加:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
rem适配方案
安装postcss-pxtorem和amfe-flexible:
npm install postcss-pxtorem amfe-flexible -D
在main.js中引入:
import 'amfe-flexible'
配置postcss.config.js:
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*'],
selectorBlackList: ['.norem']
}
}
}
vw/vh方案
安装postcss-px-to-viewport:

npm install postcss-px-to-viewport -D
配置postcss.config.js:
module.exports = {
plugins: {
'postcss-px-to-viewport': {
viewportWidth: 375,
unitPrecision: 5,
viewportUnit: 'vw',
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: false
}
}
}
媒体查询适配 在CSS中针对不同屏幕尺寸设置样式:
@media screen and (max-width: 320px) {
.container {
width: 100%;
}
}
@media screen and (min-width: 321px) and (max-width: 414px) {
.container {
width: 90%;
}
}
动态设置根字体大小 在Vue组件中监听窗口变化:
export default {
mounted() {
this.setRem()
window.addEventListener('resize', this.setRem)
},
methods: {
setRem() {
const docEl = document.documentElement
const width = docEl.clientWidth
const rem = width / 10
docEl.style.fontSize = rem + 'px'
}
},
beforeDestroy() {
window.removeEventListener('resize', this.setRem)
}
}
第三方UI库适配 使用专为移动端设计的UI库如Vant,需按文档配置rem或vw单位:

import { createApp } from 'vue'
import Vant from 'vant'
import 'vant/lib/index.css'
const app = createApp()
app.use(Vant)
图片和媒体适配 使用响应式图片处理:
<picture>
<source media="(min-width: 768px)" srcset="large.jpg">
<source media="(min-width: 320px)" srcset="medium.jpg">
<img src="small.jpg" alt="响应式图片">
</picture>
触摸事件处理
在Vue中使用@touchstart、@touchmove等替代部分点击事件:
<button @touchstart="handleTouch">按钮</button>
1px边框问题解决 使用伪元素和transform解决高清屏1px显示问题:
.border-1px {
position: relative;
}
.border-1px::after {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1px;
background: #000;
transform: scaleY(0.5);
transform-origin: 0 0;
}
禁止长按菜单 添加CSS防止长按弹出系统菜单:
* {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
}






