vue-property-decorator的簡單介紹,一看就會

參考:https://github.com/kaorun343/vue-property-decorator
怎么使vue支持ts寫法呢,我們需要用到vue-property-decorator,這個組件完全依賴于vue-class-component.

首先安裝: npm i -D vue-property-decorator

我們來看下頁面上代碼展示:

<template>
  <div>
    foo:{{foo}}
    defaultArg:{{defaultArg}} | {{countplus}}
    <button @click="delToCount($event)">點(diǎn)擊del emit</button>
    <HellowWordComponent></HellowWordComponent>
    <button ref="aButton">ref</button>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Emit, Ref } from 'vue-property-decorator';
import HellowWordComponent from '@/components/HellowWordComponent.vue';

@Component({
  components: {
    HellowWordComponent,
  },
  beforeRouteLeave(to: any, from: any, next: any) {
    console.log('beforeRouteLeave');
    next();
  },
  beforeRouteEnter(to: any, from: any, next: any) {
    console.log('beforeRouteLeave');
    next();
  },
})

export default class DemoComponent extends Vue {
  private foo = 'App Foo!';

  private count: number = this.$store.state.count;

  @Prop(Boolean) private defaultArg: string | undefined;

  @Emit('delemit') private delEmitClick(event: MouseEvent) {}

  @Ref('aButton') readonly ref!: HTMLButtonElement;

  // computed;
  get countplus () {
    return this.count;
  }

  created() {}

  mounted() {}

  beforeDestroy() {}

  public delToCount(event: MouseEvent) {
    this.delEmitClick(event);
    this.count += 1; // countplus 會累加
  }

}

</script>

<style lang="less">
...
</style>

image.gif

vue-proporty-decorator它具備以下幾個裝飾器和功能:

  • @Component
  • @Prop
  • @PropSync
  • @Model
  • @Watch
  • @Provide
  • @Inject
  • @ProvideReactive
  • @InjectReactive
  • @Emit
  • @Ref

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

@Component 裝飾器可以接收一個對象作為參數(shù)求豫,可以在對象中聲明 components ,filters棵逊,directives等未提供裝飾器的選項(xiàng)力穗,也可以聲明computed拙寡,watch

registerHooks:除了上面介紹的將beforeRouteLeave放在Component中之外,還可以全局注冊,就是registerHooks

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

Component.registerHooks([
  'beforeRouteLeave',
  'beforeRouteEnter',
]);

@Component
export default class App extends Vue {
  beforeRouteLeave(to: any, from: any, next: any) {
    console.log('beforeRouteLeave');
    next();
  }

  beforeRouteEnter(to: any, from: any, next: any) {
    console.log('beforeRouteLeave');
    next();
  }
}
</script>
image.gif

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

@Prop裝飾器接收一個參數(shù)拗踢,這個參數(shù)可以有三種寫法:

  • Constructor尔觉,例如String环戈,Number设易,Boolean等逗柴,指定 prop 的類型;
  • Constructor[]顿肺,指定 prop 的可選類型戏溺;
  • PropOptions渣蜗,可以使用以下選項(xiàng):type,default于购,required袍睡,validator

注意:屬性的ts類型后面需要加上undefined類型肋僧;或者在屬性名后面加上!斑胜,表示非null非undefined
的斷言,否則編譯器會給出錯誤提示嫌吠;

// 父組件:
<template>
  <div class="Props">
    <PropComponent :name="name" :age="age" :sex="sex"></PropComponent>
  </div>
</template>

<script lang="ts">
import {Component, Vue,} from 'vue-property-decorator';
import PropComponent from '@/components/PropComponent.vue';

@Component({
  components: {PropComponent,},
})
export default class PropsPage extends Vue {
  private name = '張三';
  private age = 1;
  private sex = 'nan';
}
</script>

// 子組件:
<template>
  <div class="hello">
    name: {{name}} | age: {{age}} | sex: {{sex}}
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop} from 'vue-property-decorator';

@Component
export default class PropComponent extends Vue {
   @Prop(String) readonly name!: string | undefined;
   @Prop({ default: 30, type: Number }) private age!: number;
   @Prop([String, Boolean]) private sex!: string | boolean;
}
</script>
image.gif

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

@PropSync裝飾器與@prop用法類似,二者的區(qū)別在于:

  • @PropSync 裝飾器接收兩個參數(shù):
    propName: string 表示父組件傳遞過來的屬性名辫诅;
    options: Constructor | Constructor[] | PropOptions@Prop的第一個參數(shù)一致凭戴;
  • @PropSync 會生成一個新的計(jì)算屬性。

注意,使用PropSync的時候是要在父組件配合.sync使用的

// 父組件
<template>
  <div class="PropSync">
    <h1>父組件</h1>
    like:{{like}}
    <hr/>
    <PropSyncComponent :like.sync="like"></PropSyncComponent>
  </div>
</template>

<script lang='ts'>
import { Vue, Component } from 'vue-property-decorator';
import PropSyncComponent from '@/components/PropSyncComponent.vue';

@Component({components: { PropSyncComponent },})
export default class PropSyncPage extends Vue {
  private like = '父組件的like';
}
</script>

// 子組件
<template>
  <div class="hello">
    <h1>子組件:</h1>
    <h2>syncedlike:{{ syncedlike }}</h2>
    <button @click="editLike()">修改like</button>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, PropSync,} from 'vue-property-decorator';

@Component
export default class PropSyncComponent extends Vue {
  @PropSync('like', { type: String }) syncedlike!: string; // 用來實(shí)現(xiàn)組件的雙向綁定,子組件可以更改父組件穿過來的值

  editLike(): void {
    this.syncedlike = '子組件修改過后的syncedlike!'; // 雙向綁定,更改syncedlike會更改父組件的like
  }
}
</script>
image.gif

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

@Model裝飾器允許我們在一個組件上自定義v-model炕矮,接收兩個參數(shù):

  • event: string 事件名么夫。
  • options: Constructor | Constructor[] | PropOptions@Prop的第一個參數(shù)一致。

注意,有看不懂的,可以去看下vue官網(wǎng)文檔, https://cn.vuejs.org/v2/api/#model

// 父組件
<template>
  <div class="Model">
    <ModelComponent v-model="fooTs" value="some value"></ModelComponent>
    <div>父組件 app : {{fooTs}}</div>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import ModelComponent from '@/components/ModelComponent.vue';

@Component({ components: {ModelComponent} })
export default class ModelPage extends Vue {
  private fooTs = 'App Foo!';
}
</script>

// 子組件
<template>
  <div class="hello">
    子組件:<input type="text" :value="checked" @input="inputHandle($event)"/>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Model,} from 'vue-property-decorator';

@Component
export default class ModelComponent extends Vue {
   @Model('change', { type: String }) readonly checked!: string

   public inputHandle(that: any): void {
     this.$emit('change', that.target.value); // 后面會講到@Emit,此處就先使用this.$emit代替
   }
}
</script>

image.gif

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

@Watch 裝飾器接收兩個參數(shù):

  • path: string 被偵聽的屬性名档痪;

  • options?: WatchOptions={} options可以包含兩個屬性 :

    immediate?:boolean 偵聽開始之后是否立即調(diào)用該回調(diào)函數(shù);
    deep?:boolean 被偵聽的對象的屬性被改變時邢滑,是否調(diào)用該回調(diào)函數(shù)腐螟;

發(fā)生在beforeCreate勾子之后,created勾子之前

<template>
  <div class="PropSync">
    <h1>child:{{child}}</h1>
    <input type="text" v-model="child"/>
  </div>
</template>

<script lang="ts">
import { Vue, Watch, Component } from 'vue-property-decorator';

@Component
export default class WatchPage extends Vue {
  private child = '';

  @Watch('child')
  onChildChanged(newValue: string, oldValue: string) {
    console.log(newValue);
    console.log(oldValue);
  }
}
</script>

image.gif

6困后,@Emit(event?: string)

  • @Emit 裝飾器接收一個可選參數(shù)乐纸,該參數(shù)是$Emit的第一個參數(shù),充當(dāng)事件名摇予。如果沒有提供這個參數(shù)汽绢,$Emit會將回調(diào)函數(shù)名的camelCase轉(zhuǎn)為kebab-case,并將其作為事件名侧戴;
  • @Emit會將回調(diào)函數(shù)的返回值作為第二個參數(shù)庶喜,如果返回值是一個Promise對象,$emit會在Promise對象被標(biāo)記為resolved之后觸發(fā)救鲤;
  • @Emit的回調(diào)函數(shù)的參數(shù),會放在其返回值之后秩冈,一起被$emit當(dāng)做參數(shù)使用本缠。
// 父組件
<template>
  <div class="">
    點(diǎn)擊emit獲取子組件的名字<br/>
    姓名:{{emitData.name}}
    <hr/>
    <EmitComponent sex='女' @add-to-count="returnPersons" @delemit="delemit"></EmitComponent>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import EmitComponent from '@/components/EmitComponent.vue';

@Component({
  components: { EmitComponent },
})
export default class EmitPage extends Vue {
  private emitData = { name: '我還沒有名字' };

  returnPersons(data: any) {
    this.emitData = data;
  }

  delemit(event: MouseEvent) {
    console.log(this.emitData);
    console.log(event);
  }
}
</script>

// 子組件
<template>
  <div class="hello">
    子組件:
    <div v-if="person">
      姓名:{{person.name}}<br/>
      年齡:{{person.age}}<br/>
      性別:{{person.sex}}<br/>
    </div>
    <button @click="addToCount(person)">點(diǎn)擊emit</button>
    <button @click="delToCount($event)">點(diǎn)擊del emit</button>
  </div>
</template>

<script lang="ts">
import {
  Component, Vue, Prop, Emit,
} from 'vue-property-decorator';

type Person = {name: string; age: number; sex: string };

@Component
export default class PropComponent extends Vue {
  private name: string | undefined;

  private age: number | undefined;

  private person: Person = { name: '我是子組件的張三', age: 1, sex: '男' };

  @Prop(String) readonly sex: string | undefined;

  @Emit('delemit') private delEmitClick(event: MouseEvent) {}

  @Emit() // 如果此處不設(shè)置別名字,則默認(rèn)使用下面的函數(shù)命名
  addToCount(p: Person) { // 此處命名如果有大寫字母則需要用橫線隔開  @add-to-count
    return this.person; // 此處不return,則會默認(rèn)使用括號里的參數(shù)p;
  }

  delToCount(event: MouseEvent) {
    this.delEmitClick(event);
  }
}
</script>

image.gif

7,@Ref(refKey?: string)

@Ref 裝飾器接收一個可選參數(shù)入问,用來指向元素或子組件的引用信息丹锹。如果沒有提供這個參數(shù)稀颁,會使用裝飾器后面的屬性名充當(dāng)參數(shù)

<template>
  <div class="PropSync">
    <button @click="getRef()" ref="aButton">獲取ref</button>
    <RefComponent name="names" ref="RefComponent"></RefComponent>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from 'vue-property-decorator';
import RefComponent from '@/components/RefComponent.vue';

@Component({
  components: { RefComponent },
})
export default class RefPage extends Vue {
  @Ref('RefComponent') readonly RefC!: RefComponent;
  @Ref('aButton') readonly ref!: HTMLButtonElement;
  getRef() {
    console.log(this.RefC);
    console.log(this.ref);
  }
}
</script>

image.gif

`8.Provide/Inject ProvideReactive/InjectReactive

@Provide(key?: string | symbol)/@Inject(options?: { from?: InjectKey, default?: any } | InjectKey)` decorator

@ProvideReactive(key?: string | symbol) / @InjectReactive(options?: { from?: InjectKey, default?: any } | InjectKey) decorator

提供/注入裝飾器,
key可以為string或者symbol類型,

相同點(diǎn):Provide/ProvideReactive提供的數(shù)據(jù),在內(nèi)部組件使用Inject/InjectReactive都可取到 不同點(diǎn):
如果提供(ProvideReactive)的值被父組件修改,則子組件可以使用InjectReactive捕獲此修改楣黍。

// 最外層組件
<template>
  <div class="">
    <H3>ProvideInjectPage頁面</H3>
    <div>
      在ProvideInjectPage頁面使用Provide,ProvideReactive定義數(shù)據(jù),不需要props傳遞數(shù)據(jù)
      然后爺爺套父母,父母套兒子,兒子套孫子,最后在孫子組件里面獲取ProvideInjectPage
      里面的信息
    </div>
    <hr/>
    <provideGrandpa></provideGrandpa> <!--爺爺組件-->
  </div>
</template>

<script lang="ts">
import {
  Vue, Component, Provide, ProvideReactive,
} from 'vue-property-decorator';
import provideGrandpa from '@/components/ProvideGParentComponent.vue';

@Component({
  components: { provideGrandpa },
})
export default class ProvideInjectPage extends Vue {
  @Provide() foo = Symbol('fooaaa');

  @ProvideReactive() fooReactive = 'fooReactive';

  @ProvideReactive('1') fooReactiveKey1 = 'fooReactiveKey1';

  @ProvideReactive('2') fooReactiveKey2 = 'fooReactiveKey2';

  created() {
    this.foo = Symbol('fooaaa111');
    this.fooReactive = 'fooReactive111';
    this.fooReactiveKey1 = 'fooReactiveKey111';
    this.fooReactiveKey2 = 'fooReactiveKey222';
  }
}
</script>

// ...provideGrandpa調(diào)用父母組件
<template>
  <div class="hello">
    <ProvideParentComponent></ProvideParentComponent>
  </div>
</template>

// ...ProvideParentComponent調(diào)用兒子組件
<template>
  <div class="hello">
    <ProvideSonComponent></ProvideSonComponent>
  </div>
</template>

// ...ProvideSonComponent調(diào)用孫子組件
<template>
  <div class="hello">
    <ProvideGSonComponent></ProvideGSonComponent>
  </div>
</template>

// 孫子組件<ProvideGSonComponent>,經(jīng)過多層引用后,在孫子組件使用Inject可以得到最外層組件provide的數(shù)據(jù)哦
<template>
  <div class="hello">
    <h3>孫子的組件</h3>
    爺爺組件里面的foo:{{foo.description}}<br/>
    爺爺組件里面的fooReactive:{{fooReactive}}<br/>
    爺爺組件里面的fooReactiveKey1:{{fooReactiveKey1}}<br/>
    爺爺組件里面的fooReactiveKey2:{{fooReactiveKey2}}
    <span style="padding-left:30px;">=> fooReactiveKey2沒有些key所以取不到哦</span>
  </div>
</template>

<script lang="ts">
import {
  Component, Vue, Inject, InjectReactive,
} from 'vue-property-decorator';

@Component
export default class ProvideGSonComponent extends Vue {
  @Inject() readonly foo!: string;

  @InjectReactive() fooReactive!: string;

  @InjectReactive('1') fooReactiveKey1!: string;

  @InjectReactive() fooReactiveKey2!: string;
}
</script>

image.gif

demo地址:https://github.com/slailcp/vue-cli3/tree/master/src/pc-project/views/manage

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末匾灶,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子租漂,更是在濱河造成了極大的恐慌阶女,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件哩治,死亡現(xiàn)場離奇詭異秃踩,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)业筏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門憔杨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蒜胖,你說我怎么就攤上這事消别。” “怎么了台谢?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵寻狂,是天一觀的道長。 經(jīng)常有香客問我对碌,道長荆虱,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任朽们,我火速辦了婚禮怀读,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘骑脱。我一直安慰自己菜枷,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布叁丧。 她就那樣靜靜地躺著啤誊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪拥娄。 梳的紋絲不亂的頭發(fā)上蚊锹,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天,我揣著相機(jī)與錄音稚瘾,去河邊找鬼牡昆。 笑死,一個胖子當(dāng)著我的面吹牛摊欠,可吹牛的內(nèi)容都是我干的丢烘。 我是一名探鬼主播柱宦,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼播瞳!你這毒婦竟也來了掸刊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤赢乓,失蹤者是張志新(化名)和其女友劉穎忧侧,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骏全,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡苍柏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了姜贡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片试吁。...
    茶點(diǎn)故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖楼咳,靈堂內(nèi)的尸體忽然破棺而出熄捍,到底是詐尸還是另有隱情,我是刑警寧澤母怜,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布余耽,位于F島的核電站,受9級特大地震影響苹熏,放射性物質(zhì)發(fā)生泄漏碟贾。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一轨域、第九天 我趴在偏房一處隱蔽的房頂上張望袱耽。 院中可真熱鬧,春花似錦干发、人聲如沸朱巨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽冀续。三九已至,卻和暖如春必峰,著一層夾襖步出監(jiān)牢的瞬間洪唐,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工吼蚁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留凭需,地道東北人。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像功炮,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子术唬,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容