Custom directives
In Vue.js, custom directives provide a way to directly manipulate the DOM and add special behaviors to elements. This article demonstrates how to create a custom search filter directive to dynamically filter a list based on user input.To create a custom search filter directive in Vue.js, you can use a custom directive. Directives in Vue.js allow you to directly manipulate the DOM and apply special behavior to elements.
Below is a detailed example of how to create a custom search filter directive in Vue.js:
<template>
<div>
<input type="text" v-model="searchText" placeholder="Search...">
<ul v-search-filter="searchText">
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Another Item' },
{ id: 4, name: 'Yet Another Item' }
],
searchText: ''
};
},
directives: {
'search-filter': {
// Directive definition
inserted: function (el, binding) {
const searchText = binding.value.toLowerCase();
const items = el.children;
// Filter items based on search text
for (let i = 0; i < items.length; i++) {
const item = items[i];
const itemName = item.textContent.toLowerCase();
if (!itemName.includes(searchText)) {
item.style.display = 'none'; // Hide the item if it doesn't match the search text
} else {
item.style.display = ''; // Show the item if it matches the search text
}
}
}
}
}
};
</script>
In this example
- We have an input field bound to the searchText data property using v-model. Users can type in the input field to enter the search text.
- We use the v-search-filter directive on the ul element to apply the search filter behavior.
- Inside the directives object of the component, we define a custom directive called search-filter.
- The inserted hook of the directive is triggered when the bound element (ul in this case) is inserted into the DOM.
- Inside the inserted hook, we retrieve the search text from the directive binding (binding.value) and filter the child elements of the bound element (which are the li items in this case).
- We iterate over each child item, compare its text content with the search text, and hide/show the item accordingly based on whether it matches the search text.
- The search filter is applied dynamically as the user types in the search input
Summary
In Vue.js, custom directives provide a way to directly manipulate the DOM and add special behaviors to elements. This article demonstrates how to create a custom search filter directive to dynamically filter a list based on user input.