一文秒懂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,})
 
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,next: any) {
    console.log('beforeRouteLeave');
    next();
  }
 
  beforeRouteEnter(to: 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,} 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,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,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,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,} 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,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,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

原文地址:https://blog.csdn.net/sllailcp/article/details/102542796

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


可以通过min-width属性来设置el-table-column的最小宽度。以下是一个示例: &lt;template&gt; &lt;el-table :data=&quot;tableData&quot;&gt; &lt;el-table-column prop=&quot;item_no&q
yarn dev,当文件变动后,会自动重启。 yanr start不会自动重启 nodemon会监听文件变动,跟yarn dev和yarn start无关。
ref 用于创建一个对值的响应式引用。这个值可以是原始值(如数字或字符串)或对象。当 ref 的值发生变化时,Vue 会自动更新 DOM 或任何其他使用该 ref 的响应式依赖。 使用示例: import { ref } from &#39;vue&#39;; const count = ref(0
通过修改 getWK005 函数来实现这一点。这里的 query 参数就是发送 GET 请求时的查询参数。你可以将需要的条件作为 query 对象的属性传递进去。比如,如果你想要按照特定的条件查询信息,你可以在调用 getWK005 函数时传递这些条件。例如: getWK005({ conditio
&lt;el-form-item label=&quot;入库类型&quot; prop=&quot;mt_type&quot;&gt; &lt;el-select v-model=&quot;form.mt_type&quot; filterable placeholder=&quot;请选择&q
API 变动 样式类名变化: 一些组件的样式类名有所变动,可能需要更新你的自定义样式。 事件名和属性名变化: 某些组件的事件名和属性名发生了变化,需要检查 Element Plus 文档 以了解详细信息。 使用 setup 函数: 在 Vue 3 中,可以使用 Composition API(如 s
安装和引入方式 Element UI (Vue 2): // main.js import Vue from &#39;vue&#39;; import ElementUI from &#39;element-ui&#39;; import &#39;element-ui/lib/theme-cha
排查400 (Bad Request)和解决这个问题,可以按照以下步骤进行: 检查URL和端点:确保URL http://127.0.0.1:8008/basicApp/BS037HModel/ 是正确的,并且该端点在服务器上存在。 检查请求参数:确认发送请求时的任何参数都是正确的,包括查询参数、请
在 Vue.js 中,&lt;template&gt; 标签是一种特殊的标签,它用于定义组件的模板,但不会直接渲染为 HTML 元素。它的主要用途是在编写组件和使用插槽时提供灵活的模板定义。以下是关于 &lt;template&gt; 标签的一些关键概念和使用示例。 基本用法 组件模板:在单文件组件
el-config-provider是Element Plus库中的一个组件,用于提供全局的配置。它是Element Plus在2.0版本中引入的新组件。 el-config-provider组件的作用是允许你在应用程序中统一配置Element Plus的一些全局属性和样式,这些配置将被应用于所有E
onMounted 是一个生命周期钩子函数,在组件挂载到 DOM 后运行。在这里你可以执行需要在组件可用后进行的操作,比如获取数据、设置订阅或初始化第三方库。 使用示例: import { onMounted } from &#39;vue&#39;; onMounted(() =&gt; { //
mt_qty: (this.temp.id &amp;&amp; this.temp.mt_qty) ? this.temp.mt_qty : event.wo_wip,在这个修正后的代码中,使用了条件三元运算符来判断 this.temp.id 是否存在且 mt_qty 是否已被赋值。如果条件成立,
Axios是一个基于Promise的易用、简洁且高效的HTTP请求插件,可以用于浏览器和Node.js。首先执行yarn命令安装依赖,安装成功时在package.json文件的dependencies下多出了Axios及其版本号,笔者写此书时,安装的版本为0.26.1,如所示。 yarn add a
async 关键字用于声明一个异步函数,这个函数会返回一个 Promise 对象。与 await 关键字配合使用时,可以在异步函数中暂停代码执行,直到 Promise 解决或拒绝,从而使异步代码的处理更简单和同步化。 使用 async 的示例 下面是一个完整的 Vue 3 组件示例,展示了如何使用
Promise 是 JavaScript 中用于处理异步操作的一种对象。它代表了一个异步操作的最终完成(或失败)及其结果值。在处理异步操作时,Promise 提供了一种更干净、更可读的方式来管理回调函数。 Promise 的状态 一个 Promise 对象有三种状态: Pending(进行中):初始
在 JavaScript 中,await 是一个用于处理异步操作的关键字。它只能在 async 函数内部使用,并且用于等待一个 Promise 对象的解析。在 Vue 3 中,await 关键字常用于在组合式 API 的 setup 函数中处理异步操作,比如数据获取。 使用 await 的示例 以下
引入样式 Element UI (Vue 2): import &#39;element-ui/lib/theme-chalk/index.css&#39;; Element Plus (Vue 3): import &#39;element-plus/dist/index.css&#39;;
-D和-S区别 安装的环境不同 -D是--save-dev的简写,会安装在开发环境中(production)中的devPendencies中 -S是--save的简写,会安装在生产环境中(development)中的dependencies中
Element-plus的徽章组件el-badge Element Plus 是一个基于 Vue.js 的 UI 组件库,它提供了一系列的常用 UI 组件供开发者使用。其中,徽章组件(el-badge)是其中之一。 徽章组件(el-badge)可以在其他元素上展示一个小圆点或者一个数字,用于标记某种
vscode element-plus/lib/theme-chalk/index.css报错路径找不到 import { createApp } from &#39;vue&#39; import &#39;./style.css&#39; import App from &#39;./App.v