• [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 {
      ...
    }

     

  • 相关阅读:
    前端插件资源
    wPaint在线绘图插件
    【剑指offer】数字数组中只出现一次(2)
    系统,特别是慢查找
    Asp.Netserver控制发展Grid实现(一个)UI转让
    JAVA连接ACCESS、MYSQL、SQLSEVER、ORACLE数据库
    u_boot启动过程中的具体分析(1)
    免费是移动互联网的第一个念头
    进入公司第五届、六个月
    Windows平台Oracle使用USE_SHARED_SOCKET角色
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7510872.html
Copyright © 2020-2023  润新知