← Back to all snippets
JAVASCRIPT

Integrating a Third-Party JavaScript Library into Vue 3

Seamlessly integrate external JavaScript libraries like a charting tool or a date picker into your Vue 3 components using lifecycle hooks and template refs.

// ChartComponent.vue
<template>
  <div>
    <h3>Monthly Sales Data</h3>
    <canvas ref="chartCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import Chart from 'chart.js/auto'; // Assuming Chart.js is installed

const chartCanvas = ref(null); // Template ref to the canvas element
let myChart = null; // To hold the Chart.js instance

const chartData = ref({
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
  datasets: [
    {
      label: 'Sales',
      data: [65, 59, 80, 81, 56, 55],
      backgroundColor: 'rgba(75, 192, 192, 0.6)',
      borderColor: 'rgba(75, 192, 192, 1)',
      borderWidth: 1,
    },
  ],
});

// Initialize the chart when the component is mounted
onMounted(() => {
  if (chartCanvas.value) {
    myChart = new Chart(chartCanvas.value, {
      type: 'bar',
      data: chartData.value,
      options: {
        responsive: true,
        maintainAspectRatio: false,
      },
    });
  }
});

// Re-render the chart if chartData changes
watch(chartData, (newData) => {
  if (myChart) {
    myChart.data = newData;
    myChart.update();
  }
}, { deep: true });

// Destroy the chart instance when the component is unmounted to prevent memory leaks
onUnmounted(() => {
  if (myChart) {
    myChart.destroy();
  }
});
</script>
How it works: Integrating third-party JavaScript libraries, especially those that directly manipulate the DOM like charting libraries, is a common task in Vue 3. This snippet demonstrates how to integrate Chart.js. A `template ref` (`chartCanvas`) is used to get a direct reference to the `<canvas>` element. The chart is initialized within the `onMounted` lifecycle hook, ensuring the DOM element is available. A `watch` listener updates the chart if its underlying data changes. Crucially, the chart instance is destroyed in the `onUnmounted` hook to prevent memory leaks, maintaining application performance and stability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs