Blog>
Snippets

Integration with Third-Party Libraries

Exemplify the use of template refs to integrate a Vue.js 3 component with a third-party library that requires direct DOM manipulation.
<template>
  <div ref="libraryContainer"></div>
</template>

<script>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import ThirdPartyLibrary from 'third-party-library'; // Example import

  export default {
    name: 'ExampleComponent',

    setup() {
      // Create a Vue reactive reference for the DOM element
      const libraryContainerRef = ref(null);

      // Instances of third-party library
      let thirdPartyInstance;

      onMounted(() => {
        if (libraryContainerRef.value) {
          // Initialize the third-party library after the component has been mounted
          thirdPartyInstance = new ThirdPartyLibrary(libraryContainerRef.value);
        }
      });

      onBeforeUnmount(() => {
        if (thirdPartyInstance) {
          // Cleanup if necessary
          thirdPartyInstance.destroy();
        }
      });

      return {
        libraryContainerRef
      };
    }
  };
</script>
This code snippet is a Vue.js 3 component that integrates a third-party library requiring direct DOM manipulation. The 'ref' provides a reference to the DOM element, which we then use to initialize the third-party library within the 'onMounted' lifecycle hook. We also handle any necessary cleanup in the 'onBeforeUnmount' lifecycle hook.