To create a custom directive in Vue.js, you can follow these steps:
// main.js
Vue.directive('highlight', {
bind(el) {
el.style.backgroundColor = 'yellow';
}
})
<div>
element.<template>
<div v-highlight>
This is a highlighted div.
</div>
</template>
// main.js
import Vue from 'vue';
import App from './App.vue';
Vue.directive('highlight', {
bind(el) {
el.style.backgroundColor = 'yellow';
}
});
new Vue({
render: h => h(App),
}).$mount('#app');
Note: When defining a directive, you can provide several lifecycle hooks such as bind
, inserted
, update
, componentUpdated
, and unbind
to perform actions at different stages of the directive's lifecycle.
That's it! You have created a custom directive in Vue.js. Now, when the component or elements using this directive are rendered, it will apply the specified behavior defined in the directive's hook functions.