【问题标题】:How to pass array to props in Vue when using Typescript and class component decorator使用Typescript和类组件装饰器时如何将数组传递给Vue中的props
【发布时间】:2019-06-11 17:31:36
【问题描述】:

我似乎无法弄清楚使用 Typescript 和类组件库将数组作为道具传递给 Vue 中的组件的正确方法。 Following the official template,我尝试了以下操作:

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

const AppProps = Vue.extend({
    props: {
        propsMessage: String,
    },
});

@Component({})
export default class Table extends AppProps {
    mounted() {
        console.log(this.propsMessage);
    }
}
</script>

在一些模板中包含这个:

<template>
  <Table :propsMessage="['This', 'is', 'Bob']" />
</template>

确实有效,并给出以下输出:

[“这个”、“是”、“鲍勃”]

这是我想要的,但这肯定不是将数组作为道具传递的正确方法?我什至没有将propsMessage 定义为String[]。做了一些研究,我发现this article 提到有一个与此问题相关的bug。此问题已得到修复,并且一直是 merged just recently。所以,现在应该有办法做到这一点,但我找不到任何关于如何正确做到这一点的文档。

【问题讨论】:

    标签: typescript class vue.js components


    【解决方案1】:

    我认为您现在实际上将参数作为字符串而不是作为字符串数组传递。我现在无法测试此代码,但它可能会将您推向正确的方向。如果您在实施时遇到问题,请告诉我。

    表格组件(Table.vue):

    <template>
        <div>
            <h1>This is my table component</h1>
        </div>
    </template>
    
    <script lang="ts">
        import { Component, Vue, Prop } from 'vue-property-decorator';
    
        @Component
        export default class Table extends Vue {
    
            @Prop({ type: Array, required: true })
            propsMessage!: string[];
    
    
            constructor()
            {
                super();
    
                console.log(this.propsMessage);
            }
        }
    </script>
    

    加载表格组件的Home组件:

    <template>
        <my-table :propsMessage="myArray"></my-table>
    </template>
    
    <script lang="ts">
    
        import Vue from 'vue';
        import Component from 'vue-class-component';
        import Table from 'WHERE-YOUR-TABLE-COMPONENT-IS-LOCATED'
    
        Vue.component('my-table', Table);
    
        @Component({
            components: { Table }
        })
        export default class Home extends Vue {
    
            myArray: Array<string> = [];
    
            constructor() {
                super();
    
                this.myArray = ['This', 'is', 'Bob'];
            }
        }
    </script>
    

    【讨论】:

    • 这似乎确实有效,但它也给了我以下警告Array type using 'Array' is forbidden for simple types. Use 'T[]' instead.。将propsMessage!: Array&lt;string&gt;; 更改为propsMessage!: string[]; 似乎确实消除了警告。
    • 很高兴听到它有效。我用你对警告的修复更新了答案。
    猜你喜欢
    • 2021-03-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多