vue实现断点渲染
vue实现断点渲染的方法
使用CSS媒体查询与v-if/v-show
通过CSS媒体查询定义不同断点的样式类,结合Vue的v-if或v-show指令控制组件渲染。
<template>
<div>
<div v-show="isMobile">移动端内容</div>
<div v-show="!isMobile">桌面端内容</div>
</div>
</template>
<script>
export default {
data() {
return {
isMobile: false
}
},
mounted() {
this.checkScreenSize();
window.addEventListener('resize', this.checkScreenSize);
},
methods: {
checkScreenSize() {
this.isMobile = window.matchMedia('(max-width: 768px)').matches;
}
},
beforeDestroy() {
window.removeEventListener('resize', this.checkScreenSize);
}
}
</script>
使用Vue自定义指令
创建自定义指令处理断点逻辑,提高代码复用性。

Vue.directive('breakpoint', {
inserted(el, binding) {
const updateVisibility = () => {
const isMatch = window.matchMedia(binding.value).matches;
el.style.display = isMatch ? 'block' : 'none';
};
updateVisibility();
window.addEventListener('resize', updateVisibility);
}
});
使用第三方库
借助vue-responsive或vue-breakpoints等库简化实现。

import VueBreakpoints from 'vue-breakpoints'
Vue.use(VueBreakpoints, {
breakpoints: {
mobile: 768,
tablet: 992,
desktop: 1200
}
})
组合式API实现
在Vue3中使用composition API响应式处理断点变化。
import { ref, onMounted, onUnmounted } from 'vue';
export function useBreakpoint() {
const isMobile = ref(false);
const updateBreakpoint = () => {
isMobile.value = window.innerWidth < 768;
};
onMounted(() => {
updateBreakpoint();
window.addEventListener('resize', updateBreakpoint);
});
onUnmounted(() => {
window.removeEventListener('resize', updateBreakpoint);
});
return { isMobile };
}
SSR兼容方案
在Nuxt.js等SSR框架中,需考虑服务端渲染时的兼容性。
export default {
data() {
return {
isMobile: process.client ? window.innerWidth < 768 : false
}
},
mounted() {
if (process.client) {
window.addEventListener('resize', this.handleResize);
}
}
}






