In my table it renders an array of users as rows in a table with <tr v-for="user in users" :key="user.id">
For the the column roles, instead of getting admin or user. The data is sending a 1 for admin and 2 for user. Is there a way that I can replace the array of that object? if its 1 = admin, 2 = user
data()
{
return {
users: []
}
getUsers()
{
axios.get(url).then(response => {
this.users = response.data.report.users
})
}
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{user.firstName}} {{user.lastName}}</td>
<td>{{user.email}}</td>
<td>{{user.role}}</td>
</tr>
</tbody>
What is between {{ }} will execute as Javascript and show the output, escaped with HTML characters. Because 1 = admin and 2 = user, we can use an array where we keep index 0 empty. For example:
<td>{{ ['', 'Admin', 'User'][user.role] }}</td>
This mapping will get index 1 or 2 out of the array and use that value as an output.
You have several ways. You can expand the response in order to have "user.role_name" or you can do it manually in your TD.
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{user.firstName}} {{user.lastName}}</td>
<td>{{user.email}}</td>
<td>
<span v-if="user.role === 1">Admin</span>
<span v-else-if="user.role === 2">User</span>
<span v-else>Guest</span>
</td>
</tr>
</tbody>
One way with computed property:
new Vue({
el: '#demo',
data() {
return {
users: [],
roles: ['admin', 'user']
}
},
computed: {
fixUsers() {
return this.users.map(u => {
return { ...u, role: this.roles[u.role-1] || 'no role' }
})
}
},
methods: {
getUsers() {
//your api call
this.users = [{id: 1, firstName: 'aaa', lastName: 'bbb', email: 'aa@aa', role: 1}, {id: 2, firstName: 'bbb', lastName: 'bbb', email: 'bb@bb', role: 2}]
}
},
mounted() {
this.getUsers()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<table>
<tbody>
<tr v-for="user in fixUsers" :key="user.id">
<td>{{user.firstName}} {{user.lastName}}</td>
<td>{{user.email}}</td>
<td>{{user.role}}</td>
</tr>
</tbody>
</table>
</div>