vue屏幕适配怎么实现
Vue 屏幕适配实现方法
使用 viewport 和 rem 方案
在 public/index.html 中通过 <meta> 标签设置 viewport,并引入 flexible.js 动态计算根字体大小:
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
<script src="path/to/flexible.js"></script>
CSS 中使用 rem 单位,建议结合预处理器:
// 假设设计稿宽度为 750px,1rem = 75px
@function rem($px) {
@return ($px / 75) + rem;
}
.box {
width: rem(150); // 实际渲染为 2rem
}
使用 CSS 媒体查询
在全局样式文件中定义响应式断点:
/* 小屏幕 */
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
/* 中等屏幕 */
@media (min-width: 769px) and (max-width: 1024px) {
.container {
padding: 20px;
}
}
/* 大屏幕 */
@media (min-width: 1025px) {
.container {
padding: 30px;
}
}
使用 postcss-pxtorem 插件
安装插件:

npm install postcss-pxtorem -D
配置 postcss.config.js:
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 75, // 1rem=75px
propList: ['*'],
selectorBlackList: ['el-'] // 排除UI框架
}
}
}
使用 Vue 计算属性动态适配
在组件中通过计算属性响应窗口变化:

export default {
computed: {
containerStyle() {
return {
width: window.innerWidth > 768 ? '80%' : '100%',
fontSize: window.innerWidth > 1024 ? '16px' : '14px'
}
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.$forceUpdate()
}
}
}
使用第三方库
安装响应式工具库:
npm install vue-responsive -S
在组件中使用:
import { useBreakpoints } from 'vue-responsive'
export default {
setup() {
const breakpoints = useBreakpoints({
mobile: 640,
tablet: 768,
desktop: 1024
})
return {
isMobile: breakpoints.smaller('tablet'),
isDesktop: breakpoints.greater('tablet')
}
}
}
SVG 矢量图形适配
对于图标等矢量元素,使用 SVG 并设置 viewBox:
<svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
<circle cx="50" cy="50" r="40" />
</svg>
以上方法可根据项目需求组合使用,通常推荐 viewport+rem 方案作为基础,配合媒体查询实现精细控制。对于复杂场景可考虑使用 ResizeObserver API 进行元素级监听。






