Mathias Hillmann
Mathias Hillmann

Reputation: 1837

How can I pass an array to a Vue component?

I am trying to pass an array to a Vue component to build a table, however i am receiving an error that says that i am passing a string instead of an array.

Component:

<template>
    <div>
        <table>
            <thead>
                <tr>
                    <th v-for="(column, index) in columns" :key="index"> {{column}}</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in items" :key="index">
                    <td v-for="(column, indexColumn) in columns" :key="indexColumn">{{item[column]}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
        props: {
            column: Array,
            item: Array,
        },
    }
</script>

How I am calling the component:

<nexdatatable column="['a','b']" item="['a','b']"></nexdatatable>

Upvotes: 0

Views: 1198

Answers (2)

Arslan Butt
Arslan Butt

Reputation: 795

Some mistakes

<th v-for="(column, index) in columns" :key="index"> {{column}}</th>

in for loop, your variable name is columns but the prop array name is column

column: Array,

it should be the same

the same mistake for the items

 <tr v-for="(item, index) in items" :key="index">

items is not defined in prop

prop should be

props: {
         columns: Array,
         items: Array,
       },

now call the component like this (you can use :cloumns or v-bind:cloumns)

<nexdatatable v-bind:columns="['a','b']" v-bind:items="['a','b']"></nexdatatable>

Upvotes: 1

Arslan Butt
Arslan Butt

Reputation: 795

You can pass the array to the prop

const app = new Vue({
 data(){
     return {
     columnArray: ['a','b'],
     itemArray: ['a','b'],
     };
 },
  methods: {
    confirm(){
    alert('hello');
    }
  }
})
app.$mount("#app")
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<nexdatatable :column="columnArray" :item="itemArray"></nexdatatable>
</div>

Upvotes: 0

Related Questions