zoukankan      html  css  js  c++  java
  • [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 {
      ...
    }

     

  • 相关阅读:
    mysql,SQL标准,多表查询中内连接,外连接,自然连接等详解之查询结果集的笛卡尔积的演化
    java:JDBC详解
    卷积在深度学习中的作用(转自http://timdettmers.com/2015/03/26/convolution-deep-learning/)
    卷积(转自wiki百科)
    windows10环境下安装Tensorflow
    3、继承与派生
    2、对象和类
    1、从C语言到C++
    使用Jupyter Notebook编写技术文档
    3、利用GDB进行程序调试
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7510872.html
Copyright © 2011-2022 走看看