typescriptvue.jsvuejs3custom-directive

How to create global custom directives in Vue 3 with Typescript


I created the app with the latest Vue cli and I'm trying to register a global custom directive with no success. Can someone maybe tell me what I'm doing wrong here?

import { createApp } from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";

const app = createApp(App);

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

app
  .use(store)
  .use(router)
  .mount("#app");

screenshot to show the issue


Solution

  • The directive v-highlight should have a value of type string like :

         <h3 v-highlight="'yellow'">highlighted using yellow</h3>
        <h3 v-highlight="'#4455ff'">highlighted using blue</h3>
    
    

    if you provided it without '' you would have the following error :

    [Vue warn]: Property "yellow" was accessed during render but is not defined on instance

    This means that your directive is looking for a data or a computed property called yellow which is not defined in your script.

    LIVE DEMO

    I raised this issue and they will fix that syntax error