關(guān)于vue-property-decorator的基礎(chǔ)使用實(shí)踐
vue-property-decorator幫助我們讓vue支持TypeScript的寫法,這個(gè)庫是基于 vue-class-component庫封裝實(shí)現(xiàn)的。
注:以下環(huán)境為 vue2.x + typescript
基本使用
基礎(chǔ)模板
和原來的vue單文件組件寫法對比,template和css區(qū)域?qū)懛ú蛔?,只是script部分的寫法有變化。
<!--HelloWorld.vue--> <template> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component export default class HelloWorld extends Vue { } </script> <style scoped> </style>
lang="ts"
表示當(dāng)前支持語言為Typescript@Component
表示當(dāng)前類為vue組件export default class HelloWorld extends Vue
表示導(dǎo)出當(dāng)前繼承vue的類
data數(shù)據(jù)定義
export default class HelloWorld extends Vue { ? ? msg: string = ""; }
data中數(shù)據(jù)屬性在類中聲明為類屬性即可
生命周期鉤子
export default class HelloWorld extends Vue { ? ? created(): void { ? ? } }
所有生命周期鉤子也可以直接聲明為類原型方法,但不能在實(shí)例本身上調(diào)用他們
method方法
export default class HelloWorld extends Vue { ? ? initData(): void { ? ? } }
method里面的方法在類中直接聲明為類原型方法即可
計(jì)算屬性
計(jì)算屬性聲明為類屬性 getter/setter
<template> ? <div class="about"> ? ? <input type="text" v-model="name"> ? </div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; @Component export default class AboutView extends Vue { ? firsrName = "Hello"; ? lastName = "Kity"; ? // getter ? get name() { ? ? return this.firsrName + " " + this.lastName; ? } ? // setter ? set name(value) { ? ? const splitted = value.split(' '); ? ? this.firsrName = splitted[0]; ? ? this.lastName = splitted[1] || ""; ? } } </script>
其他選項(xiàng)
對于其他選項(xiàng),將他們傳遞給裝飾器函數(shù)
裝飾器函數(shù)
@Component
@Component可以接收一個(gè)對象,注冊子組件
import { Component, Vue, Ref } from 'vue-property-decorator'; import HelloWorld from '@/components/HelloWorld.vue'; @Component({ ? components: { ? ? HelloWorld, ? }, }) export default class HomeView extends Vue { }
如果我們使用Vue Router時(shí),希望類組件解析他們提供的鉤子,這種情況下,可以使用 Component.registerHooks注冊這些鉤子
<template> ? <div class="about"> ? ? <h1>This is an about page</h1> ? ? <input type="text" v-model="name"> ? </div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; // 注冊路由鉤子 Component.registerHooks([ ? "beforeRouteEnter", ? "beforeRouteLeave" ]) @Component export default class AboutView extends Vue { ? // 注冊鉤子之后,類組件將他們實(shí)現(xiàn)為類原型方法 ? beforeRouteEnter(to: any, from: any, next: any) { ? ? console.log("beforeRouteEnter"); ? ? next(); ? } ? beforeRouteLeave(to: any, from: any, next: any) { ? ? console.log("beforeRouteLeave"); ? ? next(); ? } } </script>
建議將注冊代碼寫在單獨(dú)的文件中,因?yàn)槲覀儽仨氃谌魏谓M件定義之前注冊他們。import將鉤子注冊的語句放在主文件的頂部來確保執(zhí)行順序
// class-component-hooks.ts import { Component } from 'vue-property-decorator' // Register the router hooks with their names Component.registerHooks([ ? 'beforeRouteEnter', ? 'beforeRouteLeave' ])
// main.ts import './class-component-hooks' import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ ? render: h => h(App) }).$mount('#app')
@Prop
@Prop(options: (PropOptions | Constructor[] | Constructor) = {})
Constructor
,指定 prop 的類型,例如 String,Number,Boolean等Constructor[]
,指定 prop的可選類型PropOptions
,指定 type,default,required,validator等選項(xiàng)
屬性的 ts 類型后面需要設(shè)置初始類型 undefined,或者在屬性名后面加上!,表示非null和非undefined的斷言,否則編譯器給出錯(cuò)誤提示
父組件
// Test.vue <template> ? <div class="test"> ? ? <test-children :name="myname" :age="age" :sex="sex" /> ? </div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import TestChildren from "@/components/TestChildren.vue"; @Component({ ? components: { ? ? TestChildren ? } }) export default class Test extends Vue { ? private myname = "Kitty"; ? private age = 18; ? sex = "female"; } </script>
子組件
// TestChildren.vue <template> ? <div class="test-children"> ? ? <p>myname: {{ name }}</p> ? ? <p>age: {{ age }}</p> ? ? <p>sex: {{ sex }}</p> ? </div> </template>
<script lang="ts"> import { Component, Vue, Prop } from "vue-property-decorator"; @Component export default class TestChildren extends Vue { ? @Prop(String) ? readonly name!: string; ? @Prop({ default: 22, type: Number }) ? private age!: number; ? @Prop([String, Boolean]) ? sex!: string | boolean; } </script>
@PropSync
@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})
@PropSync
裝飾器接收兩個(gè)參數(shù):
propName
:string,表示父組件傳遞過來的屬性名options
:Constructor | Constructor[] | PropOptions與@Prop的第一個(gè)參數(shù)一樣
@PropSync
會(huì)生成一個(gè)新的計(jì)算屬性,所以@PropSync里面的參數(shù)名不能與定義的實(shí)例屬性同名,因?yàn)閜rop是只讀的
@PropSync與@Prop的區(qū)別是使用@PropSync,子組件可以對 peops 進(jìn)行更改,并同步到父組件。
使用 @PropSync需要在父組件綁定props時(shí)使用 .sync修飾符
父組件
<template> ? <div class="test"> ? ? <p>gender: {{ gender }}</p> ? ? <test-children :gender.sync="gender" /> ? </div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import TestChildren from "@/components/TestChildren.vue"; @Component({ ? components: { ? ? TestChildren ? } }) export default class Test extends Vue { ? gender = "喝啤酒"; } </script>
子組件
<template> ? <div class="test-children"> ? ? <p>myGender: {{ myGender }}</p> ? ? <button @click="updateMyGender">更換myGender</button> ? </div> </template>
<script lang="ts"> import { Component, Vue, PropSync } from "vue-property-decorator"; @Component export default class TestChildren extends Vue { ? @PropSync("gender", { type: String }) ? myGender!: string; ? updateMyGender() { ? ? this.myGender = "吃香蕉"; ? } } </script>
@Emit
@Emit(event?: string)
- @Emit裝飾器接收一個(gè)可選參數(shù),該參數(shù)是$emit的第一個(gè)參數(shù),作為事件名。如果第一個(gè)參數(shù)為空,@Emit修飾的事件名作為第一個(gè)參數(shù),$emit會(huì)將回調(diào)函數(shù)的camelCase轉(zhuǎn)化為kebab-case
- @Emit會(huì)將回調(diào)函數(shù)的返回值作為 $emit的第二個(gè)參數(shù)。如果返回值是一個(gè)Promise對象,$emit會(huì)在Promise對象狀態(tài)變?yōu)閞esolved之后被觸發(fā)
- @Emit回調(diào)函數(shù)的參數(shù),會(huì)放在返回值之后,作為$emit參數(shù)
父組件
<template> ? <div class="test"> ? ? <p>name:{{ name }}</p> ? ? <test-children @change-name="changeName" /> ? </div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import TestChildren from "@/components/TestChildren.vue"; @Component({ ? components: { ? ? TestChildren ? } }) export default class Test extends Vue { ? name = ""; ? changeName(val: string): void { ? ? this.name = val; ? } } </script>
子組件
<template> ? <div class="test-children"> ? ? <input type="text" v-model="value"> ? ? <button @click="changeName">修改父組件的name</button> ? </div> </template>
<script lang="ts"> import { Component, Vue, Emit } from "vue-property-decorator"; @Component export default class TestChildren extends Vue { ? value = ""; ? @Emit() ? changeName(): string { ? ? return this.value; ? } } </script>
// 上例@Emit相當(dāng)于 changeName() { ? ? this.$emit("changeName", this.value); }
@Emit() changeName(arg: string): string { ? ? return this.value; } // 相當(dāng)于 changeName(arg) { ? ? this.$emit("changeName", this.value, arg); }
@Emit("change-name") change(arg: string): string { ? ? return this.value; } // 相當(dāng)于 change(arg) { ? ? this.$emit("changeName", this.value, arg); }
@Emit() changeName(): Promise<number> { ? ? return new Promise((resolve) => { ? ? ? ? setTimeout(() => { ? ? ? ? ? ? resolve(20) ? ? ? ? }, 2000) ? ? }) } // 相當(dāng)于 changeName() { ? ? const promise = new Promise((resolve) => { ? ? ? ? setTimeout(() => { ? ? ? ? ? ? resolve(20) ? ? ? ? }, 2000) ? ? }) ? ? promise.then(val => { ? ? ?? ?this.$emit("changeName", this.val) ? ? }) }
@Ref
@Ref(refKey?: string)
@Ref接收一個(gè)可選的參數(shù),表示元素或子組件的ref引用,如果不傳參數(shù),則使用裝飾器后面的屬性名作為參數(shù)
<template> ? ? <HelloWorld ref="helloComp"/> </template>
<script lang="ts"> import { Component, Vue, Ref } from 'vue-property-decorator'; import HelloWorld from '@/components/HelloWorld.vue'; @Component({ ? components: { ? ? HelloWorld, ? }, }) export default class HomeView extends Vue { ? @Ref("helloComp") readonly helloWorld!: HelloWorld; ? mounted(): void { ? ? console.log(this.helloWorld); ? } } </script>
<template> ?? ?<HelloWorld ref="helloWorld"> </template>
<script lang="ts"> ... export default class HomeView extends Vue { ? @Ref() readonly helloWorld!: HelloWorld; } </script>
@Watch
@Watch(path: string, options: WatchOptions = {})
@Watch接收兩個(gè)參數(shù):
path
: string表示被偵聽的屬性名稱options
包含immediate?: boolean和 deep: boolean屬性
@Watch("value") ? ? valueWatch(newV: string, oldV: string) { ? ? console.log(newV, oldV); } @Watch("name", { immediate: true, deep: true }) ? ? nameWatch(newV: string, oldV: string) { ? ? console.log(newV, oldV); }
@Model
@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})
@Model允許我們在組件上自定義v-model指令,接收兩個(gè)參數(shù):
event事件名
options和 Prop接收的參數(shù)類型一樣
父組件
<template> ? <div class="test"> ? ? <p>name:{{ name }}</p> ? ? <test-children v-model="name" /> ? </div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import TestChildren from "@/components/TestChildren.vue"; @Component({ ? components: { ? ? TestChildren ? } }) export default class Test extends Vue { ? name = ""; } </script>
子組件
<template> ? <div class="test-children"> ? ? <input type="text" :value="value" @input="inputHandle($event)"> ? </div> </template>
<script lang="ts"> import { Component, Vue, Model, Emit } from "vue-property-decorator"; @Component export default class TestChildren extends Vue { ? @Model("update", { type: String }) ? readonly value!: string; ? @Emit("update") ? inputHandle(e: any): void { ? ? return e.target.value; ? } } </script>
解釋
export default class TestChildren extends Vue { ? @Model("update", { type: String }) ? readonly value!: string; } // 相當(dāng)于 export default { ? ? model: { ? ? ? ? prop: 'value', ? ? ? ? event: 'update' ? ? }, ? ? props: { ? ? ? ? value: { ? ? ? ? ? ? type: String ? ? ? ? } ? ? } }
其他
以下裝飾器后面使用到會(huì)及時(shí)補(bǔ)充,如果有不清楚的可以查看文檔
@ModelSync
@Provide
@Inject
@ProvideReactive
@InjectReactive
@VModel
Mixins
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3.0路由跳轉(zhuǎn)攜帶參數(shù)的示例詳解
這篇文章主要介紹了Vue3.0路由跳轉(zhuǎn)攜帶參數(shù)的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04Vue中watch與watchEffect的區(qū)別詳細(xì)解讀
這篇文章主要介紹了Vue中watch與watchEffect的區(qū)別詳細(xì)解讀,watch函數(shù)與watchEffect函數(shù)都是監(jiān)聽器,在寫法和用法上有一定區(qū)別,是同一功能的兩種不同形態(tài),底層都是一樣的,需要的朋友可以參考下2023-11-11vue.js todolist實(shí)現(xiàn)代碼
這篇文章主要介紹了vue.js todolist實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-10-10vuex + keep-alive實(shí)現(xiàn)tab標(biāo)簽頁面緩存功能
這篇文章主要介紹了vuex + keep-alive實(shí)現(xiàn)tab標(biāo)簽頁面緩存功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10