Directives in Vue.js are used to apply low-level reactive behavior to the DOM. We can create a directive that sorts an array of objects based on a specific property.
What is Custom directive?
A custom directive in Vue.js is a feature that allows you to extend the functionality of HTML elements. It provides a way to directly manipulate the DOM (Document Object Model) within Vue.js applications. Custom directives are essentially instructions that can be attached to elements in the Vue template, enabling you to perform tasks such as DOM manipulation, event handling, or applying conditional styles.
To create a custom directive in Vue.js that sorts an array, you can follow these steps:
Define the Directive
Define a custom directive that sorts the array.
Implement Sorting Logic
Inside the directive definition, implement the logic to sort the array.
Attach Directive
Attach the directive to the element containing the array you want to sort.
<template>
<div>
<ul v-sort-by-price="items">
<li v-for="item in items" :key="item.id">
{{ item.name }} - {{ item.price }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Apple', price: 1.5 },
{ id: 2, name: 'Banana', price: 2 },
{ id: 3, name: 'Orange', price: 1.2 }
]
};
},
directives: {
sortByPrice: {
// When the bound element is inserted into the DOM...
inserted(el, binding) {
// Get the array from the binding value
const items = binding.value;
// Sort the array based on the price property
items.sort((a, b) => a.price - b.price);
// Update the DOM with the sorted array
items.forEach((item, index) => {
el.children[index].textContent = `${item.name} - ${item.price}`;
});
}
}
}
};
</script>
In this example
- We have an array of items in the items data property, each containing an id, name, and price.
- We define a directive named sortByPrice, which will sort the array of items based on their price property.
- When the bound element is inserted into the DOM (inserted hook), the directive sorts the array and updates the DOM accordingly, displaying the sorted items.
In the template, we use the v-sort-by-price directive to bind the items array to the directive. The directive then sorts the array and updates the DOM to display the sorted items.