vue-property-decorator用法

vue-property-decorator基本用法

@Component
@Emit
@Inject
@Provice
@Prop
@Watch
@Model

使用

@Component

<script lang="ts">
    import {Vue, Component} from 'vue-property-decorator';
    @Component({
      components: {
        HolleWorld
      }
    })
    export default class "组件名" extends Vue{
        ValA: string = "hello world";
        ValB: number = 1;
    }
</script>

@Emit

vue中的事件监听,vue中提供了emit、on这两个配合使用,vue-property-decorator的使用如下所示:

<script lang="ts">
    import {Vue, Component, Emit} from 'vue-property-decorator';
    @Component
    export default class "组件名" extends Vue{
        created(){
            this.$on('emit-dome', (n: string) => {
                console.log(n)
            })
        }
        @Emit()
        emitDome(n: string){
            console.log('hello');
        }
    }
</script>

子组件触发父组件传递来的函数,父组件传递的函数为reset,子组件代码:

<script lang="ts">
    import {Vue, Component, Emit} from 'vue-property-decorator';
    @Component
    export default class "组件名" extends Vue{
      @Emit('reset')
      emitTodo(n: string){}
    }
</script>

@Watch

vue-property-decorator提供的@Watch装饰器来替换Vue中的watch属性,以此来监听值的变化

import {Vue, Component, Watch} from 'vue-property-decorator';
@Watch('child')
onChangeValue(newVal: string, oldVal: string){
    console.log("watch child");
}
@Watch('person', {immediate: true, deep: true})
onChangeValue(newVal: string, oldVal: string){
    console.log("watch person");
}

@Prop

我们在使用Vue时有时会遇到子组件接收父组件传递来的参数.我们需要定义Prop属性。比如子组件从父组件接收三个属性propA,propB,propC。

  • ValueA类型为Number
  • ValueB默认值为default value
  • ValueC类型为String或者Boolean

我们使用vue-property-decorator提供的@Prop可以将上面的代码改造为如下:

<script lang="ts">
    import {Vue, Component, Prop} from 'vue-property-decorator';

    @Component
    export default class "组件名" extends Vue{
        @Prop(Number) ValueA!: number;
        @Prop({default: 'default value'}) ValueB!: string;
        @propC([String, Boolean]) ValueC: string | boolean;
    }
</script>

@Provide、@Inject提供了一个父子组件以及兄弟组件的一种传递数据的方式,父子组件传递数据的实现方式:
父组件:

import { Component, Provide, Vue } from 'vue-property-decorator'

@Component
export class Parent extends Vue {
  @Provide('foo') foo = 'foo';
  @Provide('bar') baz = 'bar';
}

子组件:

import { Component, Inject, Vue } from 'vue-property-decorator'

@Component
export class Parent extends Vue {
  @Inject() readonly foo!: string;
  @Inject() readonly baz !: string;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。