Resize Observer

A Vue Directive to get notified whenever a given element's size changes.

Examples

<script>
export default {
  data() {
    return {
      width: 0,
      height: 0,
    };
  },
  methods: {
    handleResize({ contentRect: { width, height } }) {
      this.width = Math.round(width);
      this.height = Math.round(height);
    },
  },
};
</script>

<template>
  <div
    style="height: 400px"
    class="gl-flex gl-justify-center gl-items-center"
  >
    <div
      v-resize-observer="handleResize"
      style="height: 100%; width: 100%"
      class="gl-flex gl-relative gl-justify-center gl-items-center gl-bg-status-neutral gl-text-default"
    >
      <span class="gl-inline-block gl-p-3"> I am {{ width }}px wide and {{ height }}px high. </span>
    </div>
  </div>
</template>

Code reference

This directive can be used to get notified whenever a given element's size (width or height) changes and to retrieve the updated dimensions.

Under the hood, it leverages the Resize Observer API. If you use GitLab UI in an older browser which doesn't support the Resize Observer API, you can use a polyfill.

The directive accepts a callback as a value and passes on the received contentRect and the target element whenever a resize event gets triggered.

<script>
export default {
  data() {
    return {
      width: 0,
      height: 0,
    };
  },
  methods: {
    handleResize({ contentRect: { width, height } }) {
      this.width = width;
      this.height = height;
    },
  },
};
</script>
<template>
  <div v-gl-resize-observer-directive="handleResize">
    <p>{{ width }} x {{ height }}</p>
  </div>
</template>

The observer can be toggled on or off by passing a boolean argument to the directive:

<script>
export default {
  data() {
    return {
      shouldObserve: true,
      width: 0,
      height: 0,
    };
  },
  methods: {
    handleResize({ contentRect: { width, height } }) {
      this.width = width;
      this.height = height;
    },
  },
};
</script>
<template>
  <div v-gl-resize-observer-directive:[shouldObserve]="handleResize">
    <p>{{ width }} x {{ height }}</p>
  </div>
</template>

Last updated at: