vue 打字效果_打字稿装饰器,使Vue更具打字稿感

本文介绍了如何使用TypeScript装饰器在Vue中实现打字效果,包括安装、特性、用法和示例。@VueComponent用于注册Vue组件,@Prop将变量添加到prop对象,@Watch用于监听属性变化。示例展示了纯打字稿、带有生命周期钩子的混合对象以及如何与vue-router集成。

vue 打字效果

Vue打字稿 (vue-typescript)

Typescript decorators to make vue play nice with typescript.

打字机装饰器,以使vue与打字机配合使用。

安装 (Install)

This package has one single peer-dependancy: Vue (obviously)

该程序包具有单个对等项依赖关系:Vue(显然)

npm install --save vue-typescript

For the best experience you will want to use typings and typings install --save --global dt~vue as some decorators use these typings for input parameters. If you dont want to use them, the typed vue object will be handled as any.

为了获得最佳体验,您将要使用typings install --save --global dt~vuetypings install --save --global dt~vuetypings install --save --global dt~vue因为某些装饰器typings install --save --global dt~vue这些键入用作输入参数。 如果您不想使用它们,则键入的vue对象将被视为any

Alternatively, clone the vue-typescript-seed repo

或者,克隆vue-typescript-seed回购

特征 (Features)

  • @VueComponent - A class decorator that registers the class as a vue component

    @VueComponent-类装饰器,将类注册为vue组件

  • @Prop - A variable decorator that adds a class' variables to the prop object instead of data

    @Prop-变量修饰器,将类的变量添加到prop对象而不是数据

  • @Watch - A variable or function decorator that adds a property to the watch object mapping the desired function as handler

    @Watch-变量或函数修饰器,将属性添加到将所需函数映射为处理程序的watch对象

  • Computed Properties - to define computed properties, simply use the native typescript syntax get and set (see example below)

    计算属性 -要定义计算属性,只需使用本机打字脚本语法getset (请参见下面的示例)

用法 (Usage)

@VueComponent (@VueComponent)

There are 4 ways to call it:

有四种调用方法:

    @VueComponent     @VueComponent(element:string)     @VueComponent(options:ComponentOption)     @VueComponent(element:string, options:ComponentOption)      element - string to use as html tag      options - the same object as the one you would use when calling Vue.component

@VueComponent @VueComponent(element:string) @VueComponent(options:ComponentOption) @VueComponent(element:string, options:ComponentOption)元素-用作html标签选项的字符串-与调用Vue时使用的对象相同。零件

By default, the tag will be the snake-case version of the class name, and options will be an empty object { }

默认情况下,标记将是类名的蛇形版本,而选项将是空对象{}

@Struts (@Prop)

There are 2 ways to call it:

有两种调用方法:

    @Prop     @Prop(options:PropOption)

@Prop @Prop(options:PropOption)

     options - the same object as the one you would use defining a prop

options-与您用来定义道具的对象相同

By default, the prop will behave equivalently to having  myProp: null   in the props object. However, if you give a value to a value to a variable decorated by prop (see example below), the default property of the prop object will be set to this value. If the value if of type array or object, don't worry about wrapping it in a function like you would do in standard vue, to provide maximum type checking and intelisense, vue-typescript clones and wraps it into a function for you.

默认情况下,props的行为与props对象中的myProp: null等效。 但是,如果将值赋予由prop装饰的变量的值(请参见下面的示例),则prop对象的默认属性将设置为此值。 如果值的类型为array或object,则不必担心将其包装在函数中(就像在标准vue中一样),以提供最大的类型检查和智能感知,vue-typescript会将其克隆并将其包装为函数。

@看 (@Watch)

It can be applied to either a function or a variable, and for each application, there are 2 ways to call it:

它可以应用于函数或变量,对于每种应用程序,有两种调用方法:

    @Watch(name:string)     @Watch(name:string, options:WatchOption)

@Watch(name:string) @Watch(name:string, options:WatchOption)

     name - the name of the variable to watch (if applied to a function). Or the name of the method to call when the variable changes (if applied to a variable)      options - the same object as the one you would use defining a property on the watch object (note that defining a handler is useless as it will get replaced in any case)

name-要监视的变量的名称(如果应用于函数)。 或变量更改时调用的方法的名称(如果应用于变量)选项-与用于在watch对象上定义属性的对象相同(请注意,定义处理程序是无用的,因为它将被替换)任何状况之下)

行为 (Behaviour)

  • Variables - unless the @Prop decorator is used, all variables in a class will be returned by the data object

    变量 -除非使用@Prop装饰器,否则数据对象将返回类中的所有变量

  • Functions - all functions that do not match the name of a Vue lifecycle hook, or are defined with the get and set kewywords, will be put in the methods object. Any function named like one of the hook (ex: 'ready()') will be added as a property of the options object and not to methods (see second example), while functions defined as get/set myFunc()... will be used to create the computed object.

    函数 -所有与Vue生命周期挂钩的名称不匹配的函数,或使用getset kewywords定义的所有函数,都将放置在methods对象中。 任何名称类似钩子的函数(例如:ready()')都将被添加为options对象的属性,而不是方法(请参见第二个示例),而函数定义为get/set myFunc()...将用于创建计算对象。

  • Option Object - the option object allows to access features that may not have been implemented yet by vue-typescript, or simply offers the option to have a hybrid vanilla vue / typescript component. However, is a property is defined in bot the options obect and the class, the class variable will overwrite the one in options.

    选项对象 -选项对象允许访问vue-typescript可能尚未实现的功能,或者仅提供具有混合香草vue / typescript组件的选项。 但是,如果一个属性在bot中定义了options和class,则class变量将覆盖options中的一个。

  • Constructors - Avoid defining constructors for classes that will be decorated by @VueComponent. An instance of the object is created at load time to create a vue object and register the component, if the constructor relies on parameters, there will be 'undefined' errors as these parameters will obviously not be passed.

    构造函数 -避免为将由@VueComponent装饰的类定义构造函数。 在加载时创建该对象的实例以创建vue对象并注册该组件,如果构造函数依赖于参数,则将出现“未定义”错误,因为显然不会传递这些参数。


    **see note on behaviour of
    **请参阅有关

    new below

    new下面

例子 (Examples)

纯打字稿: (Pure Typescript:)

import * as Vue from 'vue'
import { VueComponent, Prop } from 'vue-typescript'

@VueComponent
class MyComponent {
    @Prop someProp:string;

    @Prop({
        type: String
    })
    someDefaultProp:string = 'some default value'; 

    @Prop someObjProp:{some_default:string} = {some_default: 'value'}; //vue-typescript makes sure to deep clone default values for array and object types

    @Prop someFuncProp(){ //defined functions decorated with prop are treated as the default value
        console.log('logged from default function!');
    }

    someVar:string = 'Hello!';
    
    doStuff() {
        console.log('I did stuff');
    }
}

Is equivalent in Javascript to:

在Javascript中等效于:

Vue.component('my-component', {
    props: {
        someProp:null,
        someDefaultProp : {
            type: String,
            default: 'some default value'
        },
        someObjProp: {
            default: function(){
                return {
                    default: 'value'
                }
            }
        },
        someFuncProp: {
            type: Function //if it finds the default is a function, it automatically sets the type
            default: function(){
                console.log('logged from default function!');
            }
        }
    },
    data: function(){
        return {
            someVar: 'Hello!'
        }
    },
    methods: {
        doStuff: function(){
            console.log('I did stuff');
        }
    }
})


带有生命周期挂钩的混合对象: (Hybrid Object With Lifecycle Hooks:)

import * as Vue from 'vue'
import { VueComponent, Prop } from 'vue-typescript'

@VueComponent('dope-tag', {
    watch: {
        'lookAtMe': function(old, new) {
            this.itChanged(new); 
        }
    }
})
class MyDopeComponent extends Vue { //extend Vue to get intelisense on vm functions like $broadcast()
    lookAtMe:string;

    ready() {
        this.lookAtMe = 'I\'ve changed';
    }

    itChanged(new:string) {
        this.$broadcast('New var: ' + this.lookAtMe);
    }
}

Is equivalent in Javascript to:

在Javascript中等效于:

Vue.component('dope-tag', {
    data: {
        return {
            lookAtMe: undefined
        }
    },
    methods: {
        itChanged: function(new){
            this.$broadcast('New var: ' + this.lookAtMe);
        }
    },
    watch: {
        'lookAtMe': function(old, new) {
            this.itChanged(new); 
        }
    },
    ready: function() {
        this.lookAtMe = 'I\'ve changed';
    }
})


@观看示例 (@Watch examples)

Decorator on function:

装饰器上的功能:

@VueComponent
class MyClass {
    watchMe:string = 'look at meee!';

    @Watch('watchMe')
    myFunction(new_val:string, old_val:string){
        console.log('it was: ' + old_val);
        console.log('now it\'s: ' + new_val);
    }
}

is equivalent to:

等效于:

Vue.component('my-class', {
    data: function(){
        return {
            watchMe: 'look at meee!'
        }
    },
    watch: {
        watchMe: function(new_val, old_val){
            console.log('it was: ' + old_val);
            console.log('now it\'s: ' + new_val);
        }
    }
})

Decorator on variable with options:

带有选项的变量的装饰器:

@VueComponent
class MyClas {
    @Watch('myFunction', {deep: true})
    watchMe:string = 'look at meee!';

    myFunction(new_val:string, old_val:string){
        console.log('it was: ' + old_val);
        console.log('now it\'s: ' + new_val);
    }
}

is equivalent to:

等效于:

Vue.component('my-class', {
    data: function(){
        return {
            watchMe: 'look at meee!'
        }
    },
    methods: {
        myFunction: function(new_val, old_val){
            console.log('it was: ' + old_val);
            console.log('now it\'s: ' + new_val);
        }
    }
    watch: {
        watchMe: {
            handler: 'myFunction',
            deep: true
        }
    }
})


计算属性示例 (Computed Properties example)

in typescript:

在打字稿中:

@VueComponent
class ComputedStuff {
    firstname:String = 'Jon';
    lastname:String = 'Snowflake';

    get fullname():string {
        return this.firstname + ' ' + this.lastname;
    }

    set fullname(name:string){
        var name_arr = name.split(' ');
        this.firstname = name_arr[0];
        this.lastname = name_arr[1]; //you would probably want to add checks here to prevent errors
    }

    ready(){
        this.fullname = 'Jon Snowstorm';
    }
}

javascript equivalent:

等价的javascript:

Vue.component('computed-stuff', {
    data: function(){
        return {
            firstname: 'Jon',
            lastname: 'Snowflake'
        }
    },
    computed: {
        fullname: {
            get: function(){
                return this.firstname + ' ' + this.lastname;
            },
            set: function(name:string){
                var name_arr = name.split(' ');
                this.firstname = name_arr[0];
                this.lastname = name_arr[1]; //you would probably want to add checks here to prevent errors
            }
        }
    },
    ready: function(){
        this.fullname = 'Jon Snowstorm';
    }
})


与vue-router集成 (Integration With vue-router)

vue-typescript works perfectly with vue-router:

vue-typescript与vue-router完美配合:

import * as Vue from 'vue'
import * as VueRouter from 'vue-router'
import { VueComponent } from 'vue-typescript'

@VueComponent({
    template: '<h1> Welcome Home {{guy}} </h1>' //you can use require('./home_template.html') here if you're using something like webpack
})
class HomeView {
    guy:string = 'Frank';
}

Vue.use(VueRouter);

var app = Vue.extend({});
var router = new VueRouter();

router.map({
  '/' : {
    component: HomeView
  }
});

router.start(app, '#my-app');
关于在组件类上使用new说明 (Note on using new with component classes)

Calling something like new MyComponent() will actually not construct a new MyComponent object, It will actually create a new vue component instance, with the properly formated data, methods, props, watch, etc.. objects. The class MyComponent is actually equivalent to the return of Vue.component('my-component').

调用类似new MyComponent()类的东西实际上不会构造一个新的MyComponent对象,它实际上会创建一个新的vue组件实例,并带有格式正确的数据,方法,道具,手表等。 MyComponent类实际上等效于Vue.component('my-component')

翻译自: https://vuejsexamples.com/typescript-decorators-to-make-vue-feel-more-typescripty/

vue 打字效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值