Skip to content
OSMD
Language: English
Sponsor
All guides

Docs · OSMD 3.0

OSMD in Vue

A watchEffect holds the whole life of a score: create OSMD for the element, load and render, and destroy it in the cleanup.

ScoreView.vueOSMD 3.0
<script setup>
import { useTemplateRef, watchEffect } from 'vue';
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';

const props = defineProps({ url: { type: String, required: true } });
const container = useTemplateRef('container');

watchEffect(
  (onCleanup) => {
    const osmd = new OpenSheetMusicDisplay(container.value);
    osmd
      .load(props.url)
      .then(() => osmd.render())
      .catch((error) => {
        // AbortError: url changed, or the component unmounted, before the file arrived
        if (error.name !== 'AbortError') console.error(error);
      });
    onCleanup(() => osmd.destroy());
  },
  { flush: 'post' }, // after the component's DOM exists
);
</script>

<template>
  <div ref="container"></div>
</template>

Use it like any component: <ScoreView url="/scores/my-score.musicxml" />.

With flush: 'post', the effect runs after Vue has put the component’s element into the page. It runs again when props.url changes, and Vue calls the cleanup before that and once more when the component unmounts. useTemplateRef needs Vue 3.5 or newer.

Keep the instance in a plain variable, as above. If other code in the component needs it, put it in a shallowRef rather than a ref: a ref would make the whole score object deeply reactive.

What destroy() does

osmd.destroy() is new in OSMD 3.0. It aborts a load() still in flight, releases the loaded score, removes OSMD’s resize observer, takes OSMD’s pages and cursor out of the element and ends the instance. Our CI compiles this component with Vue’s own compiler, shows a score, switches to a second one and unmounts, then checks that every OSMD instance it made is destroyed and no OSMD element is left on the page.

A url that changes while a file is still loading destroys that instance before the file arrives: its load() is rejected with an AbortError, which the catch lets pass.

Resizing

With autoResize on (the default), OSMD 3.0 watches the element’s width with a ResizeObserver and lays the score out again 200 ms after the width stopped changing. Height changes, like a phone’s address bar sliding in and out, don’t redraw the score. A render() while the element is hidden (a v-show that is off, a tab that isn’t shown) is skipped, and the score is drawn once the element has a width.

On OSMD 2.3.1

Before 3.0 there is no destroy(). On 2.3.1, dispose() comes closest: it removes OSMD’s listeners, but leaves the drawing in the element.

Next: OSMD in Angular