ResizeObserver媒体查询 vue组件

文章介绍了ResizeObserverAPI,用于监听元素尺寸变化,并展示了如何在Vue中创建响应式组件和指令,根据元素宽度自动应用样式类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原始媒体查询

@media only screen and (max-width: px) {
  
}

介绍ResizeObserver

ResizeObserver:是一项新的功能,监听元素的内容矩形大小的变更,并通知做出相应的反应。和document.onresize的功能很相似

const observer = new ResizeObserver(entries => {
  entries.forEach(entry => {
    const cr = entry.contentRect;
    console.log('Element:', entry.target);
    console.log(`Element size: ${cr.width}px x ${cr.height}px`);
    console.log(`Element padding: ${cr.top}px ; ${cr.left}px`);
  })
})

observer.observe(someElement)

浏览器的支持性

使用

作为组件

<template>
  <Responsive :breakpoints="{
    small: el => el.width <= 500
  }">
    <div slot-scope="el" :class="['post__item', { small: el.is.small }]">
      <img class="post__image" :src="post.image" />
      <div class="post__text">{{post.text}}</div>
    </div>
  </Responsive>
</template>

<script>
import { Responsive } from "vue-responsive-components"
export default {
  props: ['post'],
  components: { Responsive }
}
</script>

<style lang="scss">
.post__item {
  display: flex;
}
.post__image {
  flex: 0 0 200px;
  height: 200px;
}
.post__item.small {
  flex-direction: column;
  
  .post__image {
    flex: 0 auto;
    height: auto;
  }
}
</style>

作为指令

<template>
  <!-- Will add/remove .small if the width is less / greater -->
  <div class="post__item" v-responsive="{ small: el => el.width <= 500 }">
    <img class="post__image" :src="post.image" />
    <div class="post__text">{{post.text}}</div>
  </div>
</template>

<script>
import { ResponsiveDirective } from "vue-responsive-components"
export default {
  props: ["post"],
  directives: {
    responsive: ResponsiveDirective
  }
}
</script>

插件代码实现

npm install resize-observer-polyfill --save-dev
npm install loadsh --save-dev
import throttle from "lodash.throttle"
import ResizeObserver from "resize-observer-polyfill"

export const ResponsiveMixin = {
  data() {
    return {
      el: {
        width: 0,
        height: 0,
        is: {}
      }
    }
  },
  mounted() {
    if (
      typeof process === "undefined" ||
      (!process.server && (this.breakpoints || this.$options.breakpoints))
    ) {
      this.$nextTick(() => {
        const handleResize = throttle(entries => {
          const cr = entries[0].contentRect
          ;(this.el.width = cr.width), (this.el.height = cr.height)
          const conds = Object.assign(
            {},
            this.breakpoints || {},
            this.$options.breakpoints || {}
          )
          for (const breakpoint in conds) {
            this.$set(this.el.is, breakpoint, conds[breakpoint](this.el))
          }
        }, 200)

        const observer = new ResizeObserver(handleResize)
        if (this.$el instanceof Element) {
          observer.observe(this.$el)
        }
      })
    }
  }
}

export const Responsive = {
  data() {
    return { init: false }
  },
  props: {
    noHide: { type: Boolean, default: false },
    breakpoints: { type: Object, default: undefined }
  },
  mixins: [ResponsiveMixin],
  render(h) {
    const slot =
      (this.$scopedSlots.default && this.$scopedSlots.default(this.el)) ||
      this.$slots.defaul

    return !this.noHide && !this.init
      ? h(
          "div",
          {
            style: { visibility: "hidden" }
          },
          [slot]
        )
      : slot
  },
  mounted() {
    this.init = true
  }
}

export const ResponsiveDirective = {
  inserted(el, conds) {
    if (typeof process === "undefined" || !process.server) {
      const handleResize = throttle(entries => {
        const cr = entries[0].contentRect
        for (const breakpoint in conds.value) {
          if (conds.value[breakpoint](cr)) {
            el.classList.add(breakpoint)
          } else {
            el.classList.remove(breakpoint)
          }
        }
      }, 200)

      const observer = new ResizeObserver(handleResize)
      observer.observe(el)
    }
  }
}

export const VueResponsiveComponents = Vue => {
  Vue.component("Responsive", Responsive)
  Vue.directive("responsive", ResponsiveDirective)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值