Vue3项目匹配PC端和移动端---一套组件
只写一套组件同时适配 PC 和移动端,通过 响应式布局(弹性布局 Flexbox 、Grid) 和 CSS 媒体查询(@media), 根据屏幕宽度动态调整组件的样式,从而实现一套代码适配 PC 和移动端
没有Vue3项目,创建一个项目
npm create vite@latest my-vue-app --template vue
cd my-vue-app
npm install
npm run dev
在 src/components
目录创建组件 ResponsiveComponent.vue
<template>
<div class="responsive-container">
<h1>响应式布局示例</h1>
<div class="content">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
</div>
</template>
<script setup>
// 这里不需要额外的逻辑
</script>
<style scoped>
.responsive-container {
padding: 20px;
background-color: #f0f0f0;
text-align: center;
}
.content {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: center;
}
.box {
background-color: #409eff;
color: white;
padding: 20px;
border-radius: 8px;
flex: 1 1 calc(30% - 40px); /* 默认 PC 端:3 列 */
max-width: calc(30% - 40px);
}
/* 移动端适配 */
@media (max-width: 768px) {
.box {
flex: 1 1 100%; /* 移动端:1 列 */
max-width: 100%;
}
}
</style>
App.vue
主题切换:
Vue3+Pinia 实现主题切换-CSDN博客
<template>
<div id="app">
<ResponsiveComponent />
<h1>主题切换示例</h1>
<button @click="toggleTheme">切换主题</button>
</div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useThemeStore} from './store/themeStore'
import ResponsiveComponent from './components/ResponsiveComponent.vue'
const themeStore = useThemeStore()
// 初始化时用当前主题
onMounted(() => {
themeStore.applyTheme(themeStore.currentTheme)
})
const toggleTheme = () => {
// const newTheme = themeStore.currentTheme === 'light' ? 'blue' : 'light'
// themeStore.setTheme(newTheme)
// 多个主题切换
let themes = ['light', 'blue', 'dark', 'green']
let currentIndex = themes.indexOf(themeStore.currentTheme)
let newTheme = themes[(currentIndex + 1) % themes.length]
themeStore.setTheme(newTheme)
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
background-color: var(--bg-color);
/* color: var(--text-color); */
height: 100vh;
padding: 20px;
transition: background-color 0.3s, color 0.3s;
}
button {
background-color: var(--primary-color);
color: var(--text-color);
border: none;
}
</style>
启动项目
npm run dev
PC端
移动端
flex布局改为grid布局:
<template>
<div class="responsive-grid">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
</div>
</template>
<script setup>
// 这里不需要额外的逻辑
</script>
<style scoped>
.responsive-grid {
display: grid;
gap: 20px;
padding: 20px;
}
.item {
background-color: #409eff;
color: white;
padding: 20px;
border-radius: 8px;
text-align: center;
}
/* PC 端:3 列 */
@media (min-width: 768px) {
.responsive-grid {
grid-template-columns: repeat(3, 1fr);
}
}
/* 移动端:1 列 */
@media (max-width: 768px) {
.responsive-grid {
grid-template-columns: 1fr;
}
}
</style>