📐 Resize Observer

Monitor element size changes with v-resize directive

Example 1: Resizable Box

Use Case: Track element dimensions in real-time using ResizeObserver API.

Hint: Drag the bottom-right corner to resize the box!

{{ width }}px × {{ height }}px
⇲ Drag to resize
Content Width: {{ contentWidth }}px
Content Height: {{ contentHeight }}px
Border Box Width: {{ borderBoxWidth }}px
Border Box Height: {{ borderBoxHeight }}px
Resize Count: {{ resizeCount }}
// Resize observer with v-resize directive
<div v-resize="onResize" class="resizable-box">
  {{ width }}px × {{ height }}px
</div>

methods: {
  onResize(entries, $ctx) {
    const entry = entries[0];

    // ContentRect provides content dimensions
    this.width = Math.round(entry.contentRect.width);
    this.height = Math.round(entry.contentRect.height);

    // BorderBoxSize provides full element dimensions
    if (entry.borderBoxSize) {
      const borderBox = entry.borderBoxSize[0];
      this.borderBoxWidth = Math.round(borderBox.inlineSize);
      this.borderBoxHeight = Math.round(borderBox.blockSize);
    }

    // Access element through $ctx
    console.log('Element:', $ctx.element);
    console.log('VNode:', $ctx.vnode);
  }
}

Example 2: Custom Box Model

Use Case: Configure ResizeObserver with custom options using :options.resize attribute.

Hint: This example observes border-box dimensions instead of content-box!

{{ borderWidth }}px × {{ borderHeight }}px
⇲ Border-box measurement
Box Model: {{ resizeOptions.box }}
Border Box Width: {{ borderWidth }}px
Border Box Height: {{ borderHeight }}px
// Custom box model with :options.resize
<div
  v-resize="onBorderBoxResize"
  :options.resize="resizeOptions">
  Border-box measurement
</div>

data: {
  resizeOptions: {
    box: 'border-box'
  }
},
methods: {
  onBorderBoxResize(entries, $ctx) {
    const entry = entries[0];
    if (entry.borderBoxSize) {
      const borderBox = entry.borderBoxSize[0];
      this.borderWidth = Math.round(borderBox.inlineSize);
      this.borderHeight = Math.round(borderBox.blockSize);
    }
  }
}

Key Features

  • ResizeObserver API: Native browser API for efficient resize detection
  • Custom Options: Configure box model via :options.resize or :options
  • Context Parameter: Access element, VNode, and userData via $ctx
  • Automatic Cleanup: Observer is disconnected during the destroy phase
  • Multiple Entries: Supports observing multiple elements simultaneously
// Handler signature
onResize(entries: ResizeObserverEntry[], $ctx: LifecycleContext) {
  // entries[0].contentRect - content dimensions
  // entries[0].borderBoxSize - border box dimensions
  // entries[0].contentBoxSize - content box dimensions
  // $ctx.element - DOM element
  // $ctx.vnode - VNode instance
  // $ctx.userData - Proxy-free storage
}

// Options format (ResizeObserverOptions)
{
  box: 'content-box'  // 'content-box' | 'border-box' | 'device-pixel-content-box'
}
← Back to Examples