简体   繁体   中英

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM