Code Poet
Code Poet

Reputation: 11437

Statically passing arrays to a Vue component

I need to statically pass an array to my Vue component, called ajax-table. I can't seem to find a way to do it, so I came up with this:

<ajax-table
    header-names="Code, Name, Description, Type"
    field-names="code, name, description, major_type">
</ajax-table>

Inside the component, I do this:

export default {

    props: [
        'headerNames',
        'fieldNames'
    ],

    data: function () {

        return {
            columnHeaders: [],
            columnFields: []
        }
    },

    created() {
        this.columnHeaders = this.headerNames.split(",").map(x => x.trim());
        this.columnFields = this.fieldNames.split(",").map(x => x.trim());
    }
}

Now, columnHeaders and columnFields contain the header-names and field-names that I passed statically to the component.

My question: Is there a better way to do this?

Upvotes: 1

Views: 1120

Answers (1)

akuiper
akuiper

Reputation: 214927

You should be able to directly pass the array to props using v-bind: directive or : for short:

<ajax-table
    :header-names="['Code', 'Name', 'Description', 'Type']"
    :field-names="['code', 'name', 'description', 'major_type']">
</ajax-table>

Now props headerNames and fieldNames are arrays, which you can use in the component.

Upvotes: 2

Related Questions