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.pswp.cn/news/247348.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/247348.shtml
英文地址,請注明出處:http://en.pswp.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;對臨時…