[Vue + TS] Create Type-Safe Vue Directives in TypeScript

Directives allow us to apply DOM manipulations as side effects. We’ll show you how you can create your own Vue directive to change a component’s colors and type-safe it with TypeScript.

We’ll additionally show how you can pass objects to your directives and make them more flexible!

 

Create a directive definition:

复制代码
// color-directive.ts

import { DirectiveOptions } from 'vue'

const directive: DirectiveOptions = {
    inserted(el, node) {
        /**
         * Using value:
         * v-colorDirective={color: 'red', backgroundColor: 'blue'}
         */
        if (node.value) {
            el.style.backgroundColor = node.value.backgroundColor;
            el.style.color = node.value.color;
        }

        /**Using modifiers:
         * v-colorDirective.color
         * v-colorDirective.backgroundColor
         */
        if (node.modifiers.color){
            el.style.color = node.value;
        }

        if (node.modifiers.backgroundColor) {
            el.style.backgroundColor = node.value;
        }
    }
};

export default directive;
复制代码

 

Using directive inside component:

复制代码
<template>
  <div class="hello">
    <h1 v-colorDirective="{color: 'red', backgroundColor: 'blue'}">{{ message }}</h1>
    <button @click="clicked">Click</button>
    <router-link to="/hello-ts">Hello Ts</router-link>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import colorDirective from '../color-directive';

@Component({
  directives: {
    colorDirective
  }
})
export default class Hello extends Vue {
 ....   
}
复制代码
复制代码
<template>
    <div>
        <h3 v-colorDirective.color="'green'">HelloTs</h3>
        <router-link to="/">Hello</router-link>
    </div>
</template>
<script lang="ts">

import Vue from 'vue'
import Component from 'vue-class-component'
import colorDirective from '../color-directive';

@Component({
    directives: {
        colorDirective
    }
})
export default class HelloTs extends Vue {
  ...
}
复制代码

 

 

posted @   Zhentiw  阅读(2957)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-09-12 [Javascript] Monads
2016-09-12 [Javascript] Functor law
点击右上角即可分享
微信分享提示