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)">点击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

 

 

  • 36
    点赞
  • 121
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
### 回答1: vue-property-decorator 是一个用于简化 Vue.js 组件开发的装饰器库,而 Vue 3 是 Vue.js 的下一个主要版本。vue-property-decorator 目前仅适用于 Vue 2.x 版本,并在 Vue 3.x 中不再兼容。 Vue 3 意味着对 Vue.js 进行了大规模重写和重构,旨在提供更高性能、更小的包大小、更好的开发体验和更多功能。Vue 3 引入了许多新特性,例如 Composition API、Teleport、Suspense 等。 由于 Vue 3 中改编了大量的底层代码,vue-property-decoratorVue 3.x 中不再适用,这是因为 Vue 3 在其组件定义和交互方式上引入了一些改变。为了使现有的代码能够在 Vue 3.x 中运行,我们需要采用其他方式来替代 vue-property-decorator,用于装饰 Vue 组件的功能。 Vue 3 中提供了一种新的组合式 API - Composition API,它允许我们使用函数的形式组织和复用逻辑。通过 Composition API,我们可以在 Vue 组件中按照逻辑功能划分代码,使得组件更加清晰和可维护。虽然和 vue-property-decorator 的装饰器方式不同,但 Composition API 提供了一种更灵活和直观的方式来开发 Vue 组件。 总结来说,vue-property-decorator 是用于 Vue 2.x 版本的装饰器库,而 Vue 3.x 引入了新的 Composition API,取代了 vue-property-decorator,提供了更好的开发体验和更多的功能。所以在 Vue 3.x 中使用 vue-property-decorator 是不可行的,我们需要使用 Composition API 来替代。 ### 回答2: vue-property-decorator是一个用于在Vue组件中使用装饰器语法的库。它使我们能够更加简洁和优雅地编写Vue组件,同时提供了一些强大的功能和特性。 首先,vue-property-decorator允许我们使用装饰器来定义组件的属性,方法和计算属性。通过使用装饰器,我们可以将组件的相关代码集中在一起,使代码更加易读和易维护。例如,我们可以使用@Prop装饰器来定义组件的属性,并指定其类型和默认值。我们还可以使用@Watch装饰器来监听属性或计算属性的变化。 其次,vue-property-decorator提供了一些方便的装饰器来简化对组件生命周期钩子的使用。我们可以使用@Emit装饰器来触发自定义事件,使用@Provide装饰器来提供数据,使用@Inject装饰器来注入数据等。这些装饰器使我们能够更加方便地在组件之间进行通信和共享数据。 此外,vue-property-decorator还提供了一些装饰器来简化对Vue指令和插件的使用。通过使用@Directive装饰器,我们可以定义自定义指令并将其应用到组件中,而无需手动注册和使用指令。类似地,使用@Plugin装饰器,我们可以将第三方插件集成到组件中,从而增强组件的功能。 总而言之,vue-property-decorator是一个强大而灵活的库,它使我们能够更加方便地使用装饰器语法编写Vue组件。它提供了一些强大的功能和特性,使我们的代码更加简洁和易读。对于使用Vue 3的开发者来说,vue-property-decorator无疑是一个很好的选择。 ### 回答3: vue-property-decorator是一个用于Vue.js框架的装饰器库,它能够简化开发者在使用类风格的语法时对Vue组件属性的管理和操作。 在Vue.js 3版本中,vue-property-decorator已经进行了更新和迁移,与Vue.js 2版本的使用稍有区别。在Vue.js 3中,可以使用新的@Options装饰器以替代之前的@Component装饰器,同时也可以继续使用@property装饰器来声明和管理组件的属性。 @Options装饰器可以用于修饰一个Vue组件类,它接受一个配置对象作为参数,用来定义组件的选项和行为。例如: ``` import { Options, Vue } from 'vue-property-decorator'; @Options({ props: { message: { type: String, required: true } } }) export default class MyComponent extends Vue { // 组件的其他逻辑... } ``` 上述代码中,使用@Options装饰器修饰了一个Vue组件类,并通过props字段定义了一个名为message的属性,类型为String,且是必需的。 同时,我们仍然可以使用@property装饰器来声明和管理组件的其他属性。例如: ``` import { Options, Vue, property } from 'vue-property-decorator'; @Options({}) export default class MyComponent extends Vue { @property({ type: String }) message: string = ''; // 组件的其他逻辑... } ``` 上述代码中,使用@property装饰器修饰了一个名为message的属性,并指定了它的类型为String。 总的来说,vue-property-decorator能够简化Vue.js 3中使用类风格语法时对组件属性的管理和操作,提供了方便的装饰器来声明和定义组件的属性,并与Vue的选项和行为进行集成。使用它可以使代码更易读、更易维护。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值