Reputation: 181
I'm trying to get my component to accept json data, where I won't know in advance the name of the array or the field names
For instance if it's
"user": [
{
"id": "1",
"userid": "[email protected]",
"name": "Bob"
},
{
"id": "2",
"userid": "[email protected]",
"name": "Trev"
}
]
I'll also pass in some meta, that will specify the name and the fields. e.g.
{
name: 'user',
columns: [
"userid",
"name"
]
}
If I hard code it e.g.
<tr v-for="row in IncomingData.user">
<td>{{ row.userid }}</td>
<td>{{ row.name }}</td>
</tr>
It works, but I don't want to hard code. I've tried to see if I can specify the v-for using a string e.g.
<tr v-for="row in eval('IncomingData.user')">
But this does not work. How can I specify the names of things dynamically in vue.js templates
Upvotes: 1
Views: 3850
Reputation: 34914
If there is multiple elements lets say users
,'others' you can use another outer loop
<template v-for="inner in IncomingData">
<tr v-for="row in inner">
<td>{{ row.userid }}</td>
<td>{{ row.name }}</td>
</tr>
</template>
If there is only one element lets say users
and you just want to get first unknown key, then use
<tr v-for="row in IncomingData[Object.keys(IncomingData)[0]]">
<td>{{ row.userid }}</td>
<td>{{ row.name }}</td>
</tr>
new Vue({
el:"#app",
data:{
IncomingData:{
"user": [ {
"id": "1",
"userid": "[email protected]",
"name": "Bob"
},
{
"id": "2",
"userid": "[email protected]",
"name": "Trev"
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
By Inner Loop
<table width="100%">
<tr style="text-align:left;">
<th>User Id</th>
<th>Name</th>
</tr>
<template v-for="inner in IncomingData">
<tr v-for="row in inner">
<td>{{ row.userid }}</td>
<td>{{ row.name }}</td>
</tr>
</template>
</table>
<br/><br/>
By getting first key name
<table width="100%">
<tr style="text-align:left;">
<th>User Id</th>
<th>Name</th>
</tr>
<tr v-for="row in IncomingData[Object.keys(IncomingData)[0]]">
<td>{{ row.userid }}</td>
<td>{{ row.name }}</td>
</tr>
</table>
</div>
Upvotes: 1
Reputation: 809
You may use IncomingData[varName]
where varName
is dynamic name you want to use (e.g user
or anything else).
Upvotes: 2