vue实现响应式网页
响应式设计基础
Vue 结合 CSS 媒体查询和响应式布局技术(如 Flexbox 或 Grid)实现响应式网页。核心是通过动态数据绑定和条件渲染适配不同屏幕尺寸。
<template>
<div :class="{ 'mobile-layout': isMobile, 'desktop-layout': !isMobile }">
<p>当前设备: {{ deviceType }}</p>
</div>
</template>
<script>
export default {
data() {
return {
isMobile: false,
};
},
computed: {
deviceType() {
return this.isMobile ? '移动端' : '桌面端';
},
},
mounted() {
this.checkScreenSize();
window.addEventListener('resize', this.checkScreenSize);
},
methods: {
checkScreenSize() {
this.isMobile = window.innerWidth < 768;
},
},
};
</script>
<style>
.mobile-layout {
padding: 10px;
font-size: 14px;
}
.desktop-layout {
padding: 20px;
font-size: 16px;
}
</style>
动态组件与条件渲染
通过 Vue 的 v-if 或 <component :is=""> 动态切换组件,适配不同设备。
<template>
<component :is="currentComponent" />
</template>
<script>
import DesktopMenu from './DesktopMenu.vue';
import MobileMenu from './MobileMenu.vue';
export default {
computed: {
currentComponent() {
return window.innerWidth < 768 ? MobileMenu : DesktopMenu;
},
},
};
</script>
CSS 媒体查询集成
在 Vue 单文件组件中直接使用 CSS 媒体查询,结合 SCSS/Less 增强可维护性。
<style scoped>
.container {
width: 100%;
}
@media (min-width: 768px) {
.container {
max-width: 750px;
}
}
@media (min-width: 992px) {
.container {
max-width: 970px;
}
}
</style>
响应式工具库
使用第三方库(如 vue-responsive 或 vue-breakpoints)简化逻辑。
import VueResponsive from 'vue-responsive';
export default {
mixins: [VueResponsive],
data() {
return {
breakpoints: {
mobile: { max: 767 },
tablet: { min: 768, max: 1023 },
desktop: { min: 1024 },
},
};
},
};
视口单位与弹性布局
结合 CSS 的 vw/vh 单位和 Flex/Grid 布局实现弹性缩放。
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1vw;
}
服务端渲染(SSR)适配
若使用 Nuxt.js,可通过 $device 插件直接获取设备信息。
// Nuxt 配置
export default {
plugins: ['~/plugins/device.js'],
};
// 使用示例
if (this.$device.isMobile) {
// 移动端逻辑
}






