Computed properties in a Vue loop
How to compute properties in a template with Vue. It's pretty straight forward, the thing is, it's not related to Vue at all. Just fetch you data, add the new properties you want on it, then return the data to the Vue instance or component
by darkylmnx
HTML
<div id="app" v-cloak>
<p v-if="users === null">loading</p>
<ul>
<li v-for="user in users">
<strong>computed</strong> : {{ user.fullname }}
<br>
<strong>not computed</strong> : {{ user.name.last }} {{ user.name.first }}
</li>
</ul>
</div>
CSS
[v-cloak] {
visibility: hidden;
}
li {
list-style: none;
margin-bottom: 20px;
}
Vue
const ApiUser = {
getList(seed = 'abc', page = 1) {
// i'm using fetch but it could be axios
return fetch(`https://randomuser.me/api/?page=${page}&results=10&seed=${seed}`)
.then(resp => resp.json())
.then(json => json.results)
.then(results => results.map(UserModel))
}
}
function UserModel(user) {
// I will compute properties here
// This is independent of Vue and is done after AJAX
user.fullname = user.name.last.toUpperCase() + ' ' + user.name.first
// this will be used with a map so return
// the new user
return user
}
// HERE I START VUE LOGIC
new Vue({
el: '#app',
data: {
users: null
},
created() {
ApiUser.getList()
.then(users => (this.users = users))
}
})