Vue Typescript 组件类属性初始值设定项的最佳实践

Sam*_*num 1 typescript vue.js vue-component vuejs2

我看到很多关于 Vue + Typescript 组件类的相互矛盾的文档。

在哪里定义属性?在此处@Component概述的注释中?作为此处概述的带注释的实例属性?@Prop

在哪里初始化定义的属性?在构造函数中?在字段级属性定义中?

是否有这些东西的明确的、最新的参考资料或最新的示例应用程序?

这是我现在所拥有的:

<template>
    <div class='contacts'>

        <b-form @submit="search">
            <b-form-group>
                <b-form-input v-model="q"></b-form-input>
            </b-form-group>

            <b-button type="submit" variant="primary">Search</b-button>
        </b-form>

        <b-table :items='contacts'></b-table>
    </div>
</template>

<script lang="ts">

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

    @Component
    export default class Contacts extends Vue {
        constructor(options: any) {
            super(options);
            this.q = 'dummy data';
            this.contacts = [{
                'id': 1,
                'first_name': 'Lukas',
                'last_name': 'Stigers',
                'email': null,
                'gender': 'Male',
                'phone': '776-878-7222'
            }, {
                'id': 2,
                'first_name': 'Dari',
                'last_name': 'Matkin',
                'email': null,
                'gender': 'Female',
                'phone': '833-146-3305'
            }]
        }

        @Prop() private q: string

        @Prop() private contacts: any

        search(event:Event) {
            event.preventDefault();
            alert('You searched for ' + this.q)
        }
    }

</script>
Run Code Online (Sandbox Code Playgroud)

这有效,但我在浏览器中收到这些警告:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "q"

Cra*_*ger 6

首先,您似乎正在使用vue-property-decorator而不是vue-class-component. 您可以在vue-property-decorator 此处找到 github 页面。

其次,您收到该错误是因为您声明了一个 prop,@Prop()然后您在构造函数中设置了它的值。如果你想为你的道具​​设置一个默认值,像这样将它添加到装饰器中

@Prop({ default: 'dummy data'})
private q: string;
Run Code Online (Sandbox Code Playgroud)

如果您想q成为组件数据的一部分,只需将其定义为类上的属性,而无需装饰器,例如

private q: string = 'dummy data';
Run Code Online (Sandbox Code Playgroud)

  • `vue-class-component` 只是为您提供了 `@Component` 装饰器,并且它为其他装饰器(例如 `@Watch` 和 `@Prop`)推荐了 `vue-property-decorator`。“vue-property-decorator”实际上依赖于“vue-class-component”,因此如果您从“vue-property-decorator”导入“component”,那么您实际上正在使用“vue-class-component”。`vue-property-decorator` 只是为您提供了更多可以使用的装饰器,而不仅仅是 `@Component` 类装饰器。至少这是我的理解。 (2认同)