vue-property-decorator的基础使用实践

vue-property-decorator帮助我们让vue支持TypeScript的写法,这个库是基于 vue-class-component库封装实现的。
注:以下环境为 vue2.x + typescript

基本使用

基础模板

和原来的vue单文件组件写法对比,templatecss区域写法不变,只是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的类

data数据定义

export default class HelloWorld extends Vue {
    msg: string = "";
}

data中数据属性在类中声明为类属性即可

生命周期钩子

export default class HelloWorld extends Vue {
    created(): void {
    }
}

所有生命周期钩子也可以直接声明为类原型方法,但不能在实例本身上调用他们

method方法

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

@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

@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

@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

@Emit(event?: string)

  • @Emit装饰器接收一个可选参数,该参数是$emit的第一个参数,作为事件名。如果第一个参数为空,@Emit修饰的事件名作为第一个参数,$emit会将回调函数的camelCase转化为kebab-case
  • @Emit会将回调函数的返回值作为 $emit的第二个参数。如果返回值是一个Promise对象,$emit会在Promise对象状态变为resolved之后被触发
  • @Emit回调函数的参数,会放在返回值之后,作为$emit参数

父组件

<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

@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

@Watch(path: string, options: WatchOptions = {})

@Watch接收两个参数:

  • path: string表示被侦听的属性名称
  • options包含immediate?: booleandeep: 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指令,接收两个参数:

  • event事件名
  • optionsProp接收的参数类型一样

父组件

<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

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答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的选项和行为进行集成。使用它可以使代码更易读、更易维护。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值