vue-property-decorator帮助我们让vue支持TypeScript的写法,这个库是基于 vue-class-component库封装实现的。
注:以下环境为 vue2.x + typescript
和原来的vue单文件组件写法对比,template和css区域写法不变,只是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"
表示当前支持语言为Typescript@Component
表示当前类为vue组件export default class HelloWorld extends Vue
表示导出当前继承vue的类export default class HelloWorld extends Vue { msg: string = ""; }
data中数据属性在类中声明为类属性即可
export default class HelloWorld extends Vue { created(): void { } }
所有生命周期钩子也可以直接声明为类原型方法,但不能在实例本身上调用他们
export default class HelloWorld extends Vue { initData(): void { } }
method里面的方法在类中直接声明为类原型方法即可
计算属性声明为类属性 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>
对于其他选项,将他们传递给装饰器函数
@Component可以接收一个对象,注册子组件
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时,希望类组件解析他们提供的钩子,这种情况下,可以使用 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 { // 注册钩子之后,类组件将他们实现为类原型方法 beforeRouteEnter(to: any, from: any, next: any) { console.log("beforeRouteEnter"); next(); } beforeRouteLeave(to: any, from: any, next: any) { console.log("beforeRouteLeave"); next(); } } </script>
建议将注册代码写在单独的文件中,因为我们必须在任何组件定义之前注册他们。import将钩子注册的语句放在主文件的顶部来确保执行顺序
// 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(options: (PropOptions | Constructor[] | Constructor) = {})
Constructor
,指定 prop 的类型,例如 String,Number,Boolean等Constructor[]
,指定 prop的可选类型PropOptions
,指定 type,default,required,validator等选项属性的 ts 类型后面需要设置初始类型 undefined,或者在属性名后面加上!,表示非null和非undefined的断言,否则编译器给出错误提示
父组件
// 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(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})
@PropSync
装饰器接收两个参数:
propName
:string,表示父组件传递过来的属性名options
:Constructor | Constructor[] | PropOptions与@Prop的第一个参数一样@PropSync
会生成一个新的计算属性,所以@PropSync里面的参数名不能与定义的实例属性同名,因为prop是只读的
@PropSync与@Prop的区别是使用@PropSync,子组件可以对 peops 进行更改,并同步到父组件。
使用 @PropSync需要在父组件绑定props时使用 .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(event?: string)
父组件
<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相当于 changeName() { this.$emit("changeName", this.value); }
@Emit() changeName(arg: string): string { return this.value; } // 相当于 changeName(arg) { this.$emit("changeName", this.value, arg); }
@Emit("change-name") change(arg: string): string { return this.value; } // 相当于 change(arg) { this.$emit("changeName", this.value, arg); }
@Emit() changeName(): Promise<number> { return new Promise((resolve) => { setTimeout(() => { resolve(20) }, 2000) }) } // 相当于 changeName() { const promise = new Promise((resolve) => { setTimeout(() => { resolve(20) }, 2000) }) promise.then(val => { this.$emit("changeName", this.val) }) }
@Ref(refKey?: string)
@Ref接收一个可选的参数,表示元素或子组件的ref引用,如果不传参数,则使用装饰器后面的属性名作为参数
<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(path: string, options: WatchOptions = {})
@Watch接收两个参数:
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(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})
@Model允许我们在组件上自定义v-model指令,接收两个参数:
event事件名
options和 Prop接收的参数类型一样
父组件
<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; } // 相当于 export default { model: { prop: 'value', event: 'update' }, props: { value: { type: String } } }
以下装饰器后面使用到会及时补充,如果有不清楚的可以查看文档
@ModelSync
@Provide
@Inject
@ProvideReactive
@InjectReactive
@VModel
Mixins
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。