javascript / expert
Snippet
Lifecycle-Managed Directives for External Libraries
Integrating non-reactive libraries (like Chart.js or D3) requires careful lifecycle management. Custom directives provide a clean bridge to initialize, update, and destroy these instances exactly when the host DOM element enters or leaves the Vue virtual tree.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const vChart = {mounted(el, binding) {const chartInstance = new ThirdPartyChart(el, binding.value);el._chartInstance = chartInstance;},updated(el, binding) {el._chartInstance.update(binding.value);},beforeUnmount(el) {el._chartInstance.destroy();delete el._chartInstance;}};
vue
Breakdown
1
mounted(el, binding) { ... }
Initialize the third-party library when the element is added to the DOM.
2
el._chartInstance = chartInstance;
Attach the instance to the DOM element for later access in other hooks.
3
updated(el, binding) { ... }
React to changes in the directive's value by calling the library's update method.
4
beforeUnmount(el) { ... }
Clean up resources to prevent memory leaks before the element is removed.