vue实现屏幕适配
Vue 实现屏幕适配的方法
使用 CSS 媒体查询
通过 CSS 媒体查询根据不同屏幕尺寸应用不同的样式规则。在 Vue 组件的 <style> 标签中直接编写媒体查询代码。
@media screen and (max-width: 768px) {
.container {
width: 100%;
}
}
@media screen and (min-width: 769px) and (max-width: 1024px) {
.container {
width: 80%;
}
}
使用 Flex 布局和 Grid 布局
利用 Flex 或 Grid 布局实现弹性容器,使元素能够根据屏幕尺寸自动调整排列方式。
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.item {
flex: 1 1 200px;
}
使用 rem 或 vw/vh 单位
通过动态设置根元素的字体大小,结合 rem 单位实现适配。或者直接使用视口单位 vw 和 vh。
// 在 main.js 或 App.vue 中动态设置根字体大小
function setRem() {
const baseSize = 16;
const scale = document.documentElement.clientWidth / 1920;
document.documentElement.style.fontSize = baseSize * scale + 'px';
}
window.addEventListener('resize', setRem);
setRem();
使用第三方库
借助第三方库如 lib-flexible 或 postcss-px2rem 自动将 px 转换为 rem。

安装依赖:
npm install lib-flexible postcss-px2rem --save
在 main.js 中引入:
import 'lib-flexible'
配置 postcss-px2rem(在 vue.config.js 中):

module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-px2rem')({
remUnit: 75 // 设计稿宽度 / 10
})
]
}
}
}
}
使用 Vue 的计算属性动态调整样式
通过监听窗口大小变化,在 Vue 的计算属性中动态返回样式对象。
export default {
data() {
return {
windowWidth: window.innerWidth
}
},
computed: {
containerStyle() {
return {
width: this.windowWidth < 768 ? '100%' : '80%'
}
}
},
mounted() {
window.addEventListener('resize', () => {
this.windowWidth = window.innerWidth
})
},
beforeDestroy() {
window.removeEventListener('resize')
}
}
使用 CSS 变量
通过 CSS 变量结合 JavaScript 动态调整样式值。
:root {
--container-width: 80%;
}
@media screen and (max-width: 768px) {
:root {
--container-width: 100%;
}
}
.container {
width: var(--container-width);
}
响应式 UI 框架
直接使用响应式 UI 框架如 Element UI、Vuetify 或 Bootstrap Vue,这些框架内置了响应式布局系统。
// 例如使用 Element UI 的布局组件
<template>
<el-row :gutter="20">
<el-col :xs="24" :sm="12" :md="8" :lg="6">
<!-- 内容 -->
</el-col>
</el-row>
</template>






