当前位置:首页 > VUE

vue实现断点渲染

2026-03-09 05:49:47VUE

vue实现断点渲染的方法

使用CSS媒体查询与v-if/v-show

通过CSS媒体查询定义不同断点的样式类,结合Vue的v-ifv-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-responsivevue-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框架中,需考虑服务端渲染时的兼容性。

vue实现断点渲染

export default {
  data() {
    return {
      isMobile: process.client ? window.innerWidth < 768 : false
    }
  },
  mounted() {
    if (process.client) {
      window.addEventListener('resize', this.handleResize);
    }
  }
}

标签: 断点vue
分享给朋友:

相关文章

vue 实现回复

vue 实现回复

Vue 实现回复功能 在 Vue 中实现回复功能通常涉及表单提交、数据绑定和列表渲染。以下是实现步骤和代码示例: 数据绑定与表单 <template> <div>…

vue 实现折叠

vue 实现折叠

Vue 实现折叠功能的方法 在 Vue 中实现折叠功能可以通过多种方式完成,以下是几种常见的实现方法: 使用 v-if 或 v-show 控制显示隐藏 通过绑定一个布尔值变量,结合 v-if 或 v…

vue实现banner

vue实现banner

Vue实现Banner轮播 使用Vue实现Banner轮播可以通过第三方库如swiper或vue-awesome-swiper,也可以手动实现基础轮播效果。以下是两种常见方法: 使用vue-awes…

vue实现侧导航

vue实现侧导航

Vue 实现侧边导航 使用 Vue 实现侧边导航可以通过多种方式完成,以下是一种常见的实现方法,结合 Vue Router 和动态组件。 基础结构 创建侧边导航栏的基本结构,通常使用 <ul&…

vue实现滑动条

vue实现滑动条

Vue 实现滑动条 在 Vue 中实现滑动条可以通过原生 HTML 的 <input type="range"> 或自定义组件实现。以下是两种常见方法: 使用原生 HTML 滑动条 通过…

vue实现图片预览

vue实现图片预览

Vue 实现图片预览的方法 使用 Element UI 的 el-image 组件 Element UI 提供了 el-image 组件,支持图片预览功能。通过设置 preview-src-list…