1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It works! So, the array expression in double quotes is only evaluated if I use v-bind and not if I pass it statically?
Yep. When using v-bind, the value passed in is evaluated as javascript object, so you can pass arrays or other valid javascript object. Without it, it's simple html, so the value is considered as a string.
Brilliant! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.