In my vue project I try to sort array and return only first 3 elements but some reason I get an error.
You may have an infinite update loop in a component render function.
In my project I have two divs with v-for instruction. One of them call "newGames" computed method, second one call "mostPlayed".
If I remove one of that div from my project then everything is fine, but in other case always I have error "infinity loop".
So why does it happen? What is wrong with code. Full code bellow.
<template>
<div>
<div v-for="game in newGames" class="col-lg-4">
<div class="icon-box-3">
<div class="icon-box-icon">
<i class="fa fa-bullseye" aria-hidden="true"><div>{{formatDate(game.created_at)}}</div></i>
</div>
<div class="icon-box-content">
<h5 class="heading">{{game.title}}</h5>
<span class="text-white">{{trimText(game.description,120)}}</span>
<br>
<button @click="getGame(game.id)" type="button" class="btn btn-warning btn-sm mt-20">!Graj</button>
</div>
</div>
</div>
<div>
<div v-for="game in mostPlayed" class="col-lg-4">
<div class="card course-card">
<div class="course-head">
<a v-on:click.stop="getGame(game.id)" class="course-link"><i class="fa fa-link" aria-hidden="true"></i></a>
</div>
<div class="course-detail">
<h4 class="heading">{{game.title}}</h4>
<span class="brief">{{game.description.substr(0,60)}}</span>
<ul class="course-features">
<li><i class="fa fa-gamepad"></i> {{game.game_played}}</li>
<li><i class="fa fa-clock-o"></i> {{game.game_length}}</li>
</ul>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import {mapActions,mapGetters} from 'vuex';
export default {
name: 'Main',
data: function() {
return {
games: [],
}
},
computed: {
mostPlayed(){
let newArray = this.games.sort(function(a, b) {
return b.game_played - a.game_played;
});
return newArray.slice(0,3);
},
newGames(){
let newArray = this.games.sort(function(a, b) {
a = new Date(a.created_at).getTime();
b = new Date(b.created_at).getTime();
return b - a;
});
return newArray.slice(0,3);
}
},
methods:{
...mapActions(['getGame']),
loadGames(){
axios.get('/games',{ headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': this.getToken,
}}).then(response=>{
this.games = response.data;
}).catch(function (error) {
console.log(error);
});
},
formatDate(date){
return date.substr(2,8)
},
trimText(text,long){
if(text.length <= long){
return text;
}
return text.substr(0,long)+'...';
}
},
beforeMount(){
this.loadGames();
}
}
</script>
Thank you.