drunkdolphin
drunkdolphin

Reputation: 797

How to make custom directive in Vue.js 3?

I am following the guide of Custom Directive to create a custom directive in Vue.js 3. I made a directive to change background of an element.

Home.vue includes usage of the custom directive and main.js includes the custom direcive definition.

"Home.vue"

<template>
    <p v-highlight="yellow">Home</p>
</template>

"main.js"

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

app.mount('#app');
app.directive("highlight",{
    beforeMount(el, binding){
        el.style.background = binding.value
    }
});

But I get the following error in console:

"Cannot read property 'created' of undefined"

Does anyone help me?

Upvotes: 4

Views: 2601

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

simply change the order of mount/directive

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

app.directive("highlight",{
    beforeMount(el, binding){
        el.style.background = binding.value
    }
});
app.mount('#app');

or you can do

app.directive("highlight",{
    beforeMount(el, binding){
        el.style.background = binding.value
    }
}).mount('#app');

Upvotes: 5

Related Questions