参考: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)">点击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>
vue-proporty-decorator它具备以下几个装饰器和功能:
@Component
@Prop
@PropSync
@Model
@Watch
@Provide
@Inject
@ProvideReactive
@InjectReactive
@Emit
@Ref
1.@Component(options:ComponentOptions = {})
@Component 装饰器可以接收一个对象作为参数,可以在对象中声明 components ,filters,directives等未提供装饰器的选项,也可以声明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>
2.@Prop(options: (PropOptions | Constructor[] | Constructor) = {})
@Prop装饰器接收一个参数,这个参数可以有三种写法:
Constructor,例如String,Number,Boolean等,指定 prop 的类型;
Constructor[],指定 prop 的可选类型;
PropOptions,可以使用以下选项: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>
3,@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})
@PropSync装饰器与@prop用法类似,二者的区别在于:
@PropSync 装饰器接收两个参数:
propName: string 表示父组件传递过来的属性名;
options: Constructor | Constructor[] | PropOptions 与@Prop的第一个参数一致;
@PropSync 会生成一个新的计算属性。
注意,使用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; // 用来实现组件的双向绑定,子组件可以更改父组件穿过来的值 editLike(): void { this.syncedlike = '子组件修改过后的syncedlike!'; // 双向绑定,更改syncedlike会更改父组件的like } } </script>
4.@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})
@Model装饰器允许我们在一个组件上自定义v-model,接收两个参数:
event: string 事件名。
options: Constructor | Constructor[] | PropOptions 与@Prop的第一个参数一致。
注意,有看不懂的,可以去看下vue官网文档, 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>
5,@Watch(path: string, options: WatchOptions = {})
@Watch 装饰器接收两个参数:
path: string 被侦听的属性名;
options?: WatchOptions={} options可以包含两个属性 :
immediate?:boolean 侦听开始之后是否立即调用该回调函数;
deep?:boolean 被侦听的对象的属性被改变时,是否调用该回调函数;
发生在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>
6,@Emit(event?: string)
@Emit 装饰器接收一个可选参数,该参数是$Emit的第一个参数,充当事件名。如果没有提供这个参数,$Emit会将回调函数名的camelCase转为kebab-case,并将其作为事件名;
@Emit会将回调函数的返回值作为第二个参数,如果返回值是一个Promise对象,$emit会在Promise对象被标记为resolved之后触发;
@Emit的回调函数的参数,会放在其返回值之后,一起被$emit当做参数使用。
// 父组件 <template> <div class=""> 点击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)">点击emit</button> <button @click="delToCount($event)">点击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() // 如果此处不设置别名字,则默认使用下面的函数命名 addToCount(p: Person) { // 此处命名如果有大写字母则需要用横线隔开 @add-to-count return this.person; // 此处不return,则会默认使用括号里的参数p; } delToCount(event: MouseEvent) { this.delEmitClick(event); } } </script>
7,@Ref(refKey?: string)
@Ref 装饰器接收一个可选参数,用来指向元素或子组件的引用信息。如果没有提供这个参数,会使用装饰器后面的属性名充当参数
<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>
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类型,
相同点:Provide/ProvideReactive提供的数据,在内部组件使用Inject/InjectReactive都可取到
不同点:
如果提供(ProvideReactive)的值被父组件修改,则子组件可以使用InjectReactive捕获此修改。
// 最外层组件 <template> <div class=""> <H3>ProvideInjectPage页面</H3> <div> 在ProvideInjectPage页面使用Provide,ProvideReactive定义数据,不需要props传递数据 然后爷爷套父母,父母套儿子,儿子套孙子,最后在孙子组件里面获取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调用父母组件 <template> <div class="hello"> <ProvideParentComponent></ProvideParentComponent> </div> </template> // ...ProvideParentComponent调用儿子组件 <template> <div class="hello"> <ProvideSonComponent></ProvideSonComponent> </div> </template> // ...ProvideSonComponent调用孙子组件 <template> <div class="hello"> <ProvideGSonComponent></ProvideGSonComponent> </div> </template> // 孙子组件<ProvideGSonComponent>,经过多层引用后,在孙子组件使用Inject可以得到最外层组件provide的数据哦 <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>
demo地址:https://github.com/slailcp/vue-cli3/tree/master/src/pc-project/views/manage