vue-property-decorator使用指南

在Vue中使用TypeScript时,非常好用的一个库,使用装饰器来简化书写。

一、安装

npm i -S vue-property-decorator

  • @Prop
  • @PropSync
  • @Provide
  • @Model
  • @Watch
  • @Inject
  • @Provide
  • @Emit
  • @Component (provided by vue-class-component)
  • Mixins (the helper function named mixins provided by vue-class-component)

二、用法

1、@Component(options:ComponentOptions = {})

@Component 装饰器可以接收一个对象作为参数,可以在对象中声明 components ,filters,directives 等未提供装饰器的选项

虽然也可以在 @Component 装饰器中声明 computed,watch 等,但并不推荐这么做,因为在访问 this 时,编译器会给出错误提示

即使没有组件也不能省略@Component,否则会报错。

import {Component,Vue} from 'vue-property-decorator';
import {componentA,componentB} from '@/components';@Component({components:{componentA,componentB,},directives: {focus: {// 指令的定义inserted: function (el) {el.focus()}}}
})
export default class YourCompoent extends Vue{}

2、@Prop(options: (PropOptions | Constructor[] | Constructor) = {}) 

父子组件之间值的传递

@Prop 装饰器接收一个参数,这个参数可以有三种写法:

  • Constructor ,例如 String,Number,Boolean 等,指定 prop 的类型;
  • Constructor[] ,指定 prop 的可选类型;
  • PropOptions ,可以使用以下选项: type,default,required,validator 。

 

import { Vue, Component, Prop } from 'vue-property-decorator'@Componentexport default class MyComponent extends Vue {@Prop(String) propA: string | undefined@Prop([String, Number]) propB!: string | number@Prop({type: String,default: 'abc'})propC!: string}

等同于下面的 js 写法

export default {props: {propA: {type: Number},propB: {default: 'default value'},propC: {type: [String, Boolean]}}
}

注意:

  • 属性的ts类型后面需要加上 undefined 类型;或者在属性名后面加上!,表示 非null 和 非undefined的断言,否则编译器会给出错误提示;
  • 指定默认值必须使用上面例子中的写法,如果直接在属性名后面赋值,会重写这个属性,并且会报错。

3、@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})

  • @PropSync 装饰器与 @prop 用法类似,二者的区别在于:
  • @PropSync 装饰器接收两个参数: 

propName: string 表示父组件传递过来的属性名; 

options: Constructor | Constructor[] | PropOptions 与 @Prop 的第一个参数一致;

@PropSync 会生成一个新的计算属性。

import { Vue, Component, PropSync } from 'vue-property-decorator'@Componentexport default class MyComponent extends Vue {@PropSync('propA', { type: String, default: 'abc' }) syncedPropA!: string}

等同于下面的 js 写法

export default {props: {propA: {type: String,default: 'abc'}},computed: {syncedPropA: {get() {return this.propA},set(value) {this.$emit('update:propA', value)}}}
}

注意: @PropSync 需要配合父组件的 .sync 修饰符使用

 

在说vue 修饰符sync前,我们先看下官方文档:vue .sync 修饰符,里面说vue .sync 修饰符以前存在于vue1.0版本里,但是在在 2.0 中移除了 .sync 。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。
示例代码如下:

<comp :foo.sync="bar"></comp>

会被扩展为:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:

this.$emit('update:foo', newValue)

4、@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})

@Model 装饰器允许我们在一个组件上自定义 v-model ,接收两个参数:

event: string 事件名。

options: Constructor | Constructor[] | PropOptions 与 @Prop 的第一个参数一致。

import { Vue, Component, Model } from 'vue-property-decorator'@Componentexport default class MyInput extends Vue {@Model('change', { type: String, default: '123' }) value!: string}

等同于下面的 js 写法

export default {model: {prop: 'value',event: 'change'},props: {value: {type: String,default: '123'}}
}

上面例子中指定的是 change 事件,所以我们还需要在 template 中加上相应的事件:

<template><inputtype="text":value="value"@change="$emit('change', $event.target.value)"/></template>

对 自定义v-model 不太理解的同学,可以查看 自定义事件

 

5、@Watch(path: string, options: WatchOptions = {})

@Watch 装饰器接收两个参数:

path: string 被侦听的属性名;
options?: WatchOptions={} options 可以包含两个属性 :

immediate?:boolean 侦听开始之后是否立即调用该回调函数;

deep?:boolean 被侦听的对象的属性被改变时,是否调用该回调函数;

侦听开始,发生在 beforeCreate 勾子之后, created 勾子之前

import { Vue, Component, Watch } from 'vue-property-decorator'@Componentexport default class MyInput extends Vue {@Watch('msg')onMsgChanged(newValue: string, oldValue: string) {}@Watch('arr', { immediate: true, deep: true })onArrChanged1(newValue: number[], oldValue: number[]) {}@Watch('arr')onArrChanged2(newValue: number[], oldValue: number[]) {}}

等同于下面的 js 写法

export default {watch: {msg: [{handler: 'onMsgChanged',immediate: false,deep: false}],arr: [{handler: 'onArrChanged1',immediate: true,deep: true},{handler: 'onArrChanged2',immediate: false,deep: false}]},methods: {onMsgVhanged(newValue, oldValue) {},onArrChange1(newValue, oldValue) {},onArrChange2(newValue, oldValue) {}}
}

6、@Emit(event?: string)

  • @Emit 装饰器接收一个可选参数,该参数是 $Emit 的第一个参数,充当事件名。如果没有提供这个参数, $Emit 会将回调函数名的 camelCase 转为 kebab-case ,并将其作为事件名;
  • @Emit 会将回调函数的返回值作为第二个参数,如果返回值是一个 Promise 对象, $emit 会在 Promise 对象被标记为 resolved 之后触发;
  • @Emit 的回调函数的参数,会放在其返回值之后,一起被 $emit 当做参数使用。
import { Vue, Component, Emit } from 'vue-property-decorator'@Component
export default class MyComponent extends Vue {count = 0@Emit()addToCount(n: number) {this.count += n}@Emit('reset')resetCount() {this.count = 0}@Emit()returnValue() {return 10}@Emit()onInputChange(e) {return e.target.value}@Emit()promise() {return new Promise(resolve => {setTimeout(() => {resolve(20)}, 0)})}
}

等同于下面的 js 写法

export default {data() {return {count: 0}},methods: {addToCount(n) {this.count += nthis.$emit('add-to-count', n)},resetCount() {this.count = 0this.$emit('reset')},returnValue() {this.$emit('return-value', 10)},onInputChange(e) {this.$emit('on-input-change', e.target.value, e)},promise() {const promise = new Promise(resolve => {setTimeout(() => {resolve(20)}, 0)})promise.then(value => {this.$emit('promise', value)})}}}

7、@Ref(refKey?: string)

@Ref 装饰器接收一个可选参数,用来指向元素或子组件的引用信息。如果没有提供这个参数,会使用装饰器后面的属性名充当参数

import { Vue, Component, Ref } from 'vue-property-decorator'import { Form } from 'element-ui'@Componentexport default class MyComponent extends Vue {@Ref() readonly loginForm!: Form@Ref('changePasswordForm') readonly passwordForm!: Formpublic handleLogin() {this.loginForm.validate(valide => {if (valide) {// login...} else {// error tips}})}}

等同于下面的 js 写法

export default {computed: {loginForm: {cache: false,get() {return this.$refs.loginForm}},passwordForm: {cache: false,get() {return this.$refs.changePasswordForm}}}}

@Provide/@Inject 和 @ProvideReactive/@InhectReactive

由于平时基本不用到provide/inject选项,暂时先放着,之后再补充

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/247348.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java生鲜电商平台-统一异常处理及架构实战

Java生鲜电商平台-统一异常处理及架构实战 补充说明&#xff1a;本文讲得比较细&#xff0c;所以篇幅较长。 请认真读完&#xff0c;希望读完后能对统一异常处理有一个清晰的认识。 背景 软件开发过程中&#xff0c;不可避免的是需要处理各种异常&#xff0c;就我自己来说&…

VScode新建自定义模板快捷方式

VS新建vue文件的自定义模板 在使用vscode开发的时候&#xff0c;新建vue文件是不可或缺的&#xff0c;但是VSCode并没有vue文件的初始化模板&#xff0c;这个需要自定义模板。 我们可以使用vscode的snippets在新建.vue 文件后轻松获得一套模板。 具体步骤 打开VSCode -> …

ESLint Unary operator ‘++‘ used.

ESLint Unary operator used. 安装了ESLint&#xff0c;用这个工具之后发现居然不会写代码了。好尴尬~ 感觉自己以前写的JS都是假的... 没有操作 increment(state) {state.count ; },for(let i 0; i < temp.length; i} {//... } 然后报了如下错误 Unary operator u…

sencha touch笔记(6)——路由控制(1)

做项目的时候在界面的跳转上遇到了挺大的问题&#xff0c;本来跳转不想通过路由来控制的&#xff0c;没办法&#xff0c;只能再去看一下路由的跳转方式了。 应用程序的界面发生改变后&#xff0c;可以通过路由让应用程序的界面返回到改变之前的状态&#xff0c;例如浏览器中页面…

Angular rxjs operators 笔记

toArray /*toArray把结果都塞到数组里去 */ const source = interval(1000); const example = source.pipe(take(10),toArray() );example.subscribe(val => console.log(val)); // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] toArray /*pairwise把相邻的两个流组成数组 */…

Angular rxjs Subject笔记

BehaviorSubject /*ehaviorSubject接受一个默认参数,相当于new Subject后自动next(aa)之后到行为和Subject一致 */ const behave = new BehaviorSubject(aa); behave.subscribe(res => {console.log(res)

面试39 MySQL读写分离

&#xff08;1&#xff09;如何实现mysql的读写分离&#xff1f; 其实很简单&#xff0c;就是基于主从复制架构&#xff0c;简单来说&#xff0c;就搞一个主库&#xff0c;挂多个从库&#xff0c;然后我们就单单只是写主库&#xff0c;然后主库会自动把数据给同步到从库上去。 …

Angular自学笔记(一)ngModule 元数据

工作硬上开发angular项目,好难啊,上网搜资料教程真的贼少,吐槽真的没什么人用angular,自己学习到处搜集整理的笔记,分享出来,方便查看理解总结。应该适用于angular11系列(更新真快,反正我也不知道之前低版本不同 手动狗头) 什么是angular module(ngModule)? angula…

cookbook_数据结构和算法

1.1将数据分解为单独的变量list_a [1,2,3,4,5,6,7,8,9] a,b,c,d,e,f,g,h,i list_a print(a,b,c,d,e,f,g,h,i) #使用相等数量的参数来接收_,b,c,d,e,f,g,h,_ list_a print(b,c,d,e,f,g,h) #不要的数据使用一个没有用的变量接收 View Code1.2从任意长度的可迭代对象中分解元素…

Angular自学笔记(二)显示数据 绑定属性

显示数据 1.显示数据 ng的模版中,默认用双大括号{{}}绑定组件中的变量显示出来 import {Component } from @angular/core; @Component({selector: app-root,template: `<h1>{{title}}</h1><h2>My favorite hero is: {{myHero}}</h2>`

机器学习概览

什么是机器学习&#xff1f; 广义概念&#xff1a; 机器学习是让计算机具有学习的能力&#xff0c;无需明确的编程 —— 亚瑟萨缪尔&#xff0c;1959 工程概念&#xff1a; 计算机程序利用经验 E 学习任务 T&#xff0c;性能是 P&#xff0c;如果针对任务 T 的性能 P 随着经验 …

Angular自学笔记(?)TemplateRef和ViewContainerRef

ElementRef 由于ng是跨平台的为了减少视图层和渲染层的耦合也为了让ng更适应多平台,ng帮我们封装了ElementRef,我们可以通过ElementRef拿到native元素(在浏览器中也就是我们常说的DOM元素) 下面我们看一段代码 import {Component, ElementRef, AfterViewInit } from @angu…

python之re模块

re模块 re&#xff08;正则&#xff09;简介 ​ 正则就是用一些具有特殊含义的符号组合到一起&#xff08;称为正则表达式&#xff09;来描述字符或者字符串的方法。或者说&#xff1a;正则就是用来描述一类事物的规则。 re元字符 元字符匹配内容\w匹配字母&#xff08;包含中文…

Angular自学笔记(?)ViewChild和ViewChildren

ViewChild 最好在ngAfterViewInit之后,获取模版上的内容 获取普通dom import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from @angular/core;@Component({selector: app-view-child

IPropertySet接口

Members AllProperties MethodsDescriptionCountThe number of properties contained in the property set.包含属性个数GetAllPropertiesThe name and value of all the properties in the property set.GetPropertiesThe values of the specified properties.GetPropertyThe …

Angular自学笔记(?)ContentChild和ContentChildren

ContentChild 用法类似ViewChild, 获取投影中到组件或指令还有元素dom等 获取投影中但组件 import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from @angular/core;@Component({selector: app-content-child-panel,templateUrl

Angular自学笔记(?)属性型指令

基本概念 用于改变DOM元素的外观或行为的指令 组件是一种特殊的指令 import {Component} from @angular/core; @Component({selector: app-root,template: `<!--<app-for></app-for>--><div app-for>dasfsada</div>`,

SNS编年史

准备起草。转载于:https://www.cnblogs.com/cmleung/archive/2009/11/26/1611546.html

Angular自学笔记(?)结构型指令

内置指令的展开写法 ngIf import {Component } from @angular/core; @Component({selector: app-root,template: `<button (click)="show = !show">toggle</button><p *ngIf="show as aa">一段文字 {{ aa }}</p><ng-template…

SQL on and 和 on where 的区别

on and 和 on where 的 区别 在使用 left join 时, on and 和 on where 会有区别&#xff1b;1. on的条件是在连接生成临时表时使用的条件,以左表为基准 ,不管on中的条件真否,都会返回左表中的记录  on 后面 and 都是对右表进行筛选 2.where是全部连接完后&#xff0c;对临时…