I have a page that displays the birthdays per month of the teams. With two buttons that allow you to change the current month.
The solution with v-if works fine but since it is not a good practice I try with a computed property.
<tr v-for="birthday in birthdays" :key="birthday.name" v-if="birthday.month[month]">
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="text-sm font-medium text-gray-900">
{{ birthday.name }}
Sample data of birthdays :
[
{
"month": {
"1": false,
"2": false,
"3": true,
"4": false,
"5": false,
"6": true,
"7": true,
"8": false,
"9": true,
"10": false,
"11": true,
"12": false
},
"name": "team 2"
},
{
"month": {
"1": false,
"2": false,
"3": true,
"4": false,
"5": false,
"6": true,
"7": true,
"8": false,
"9": true,
"10": false,
"11": true,
"12": false
},
"name": "team 1"
}
]
and my code with the computed property :
export default {
data() {
return {
birthdays: {},
month: false,
};
},
async asyncData({ $axios, store }) {
let email = store.state.auth.user.email;
let month = new Date().getMonth() 1;
let { data } = await $axios.get("/birthday/?email=" email);
return { birthdays: data, month: month };
},
methods: {
nextMonth() {
if (this.month === 12) {
this.month = 1;
} else this.month = this.month 1;
},
previousMonth() {
if (this.month === 1) {
this.month = 12;
} else this.month = this.month - 1;
},
},
computed: {
fiestas: function () {
let birthdays = this.birthdays;
for (let team in birthdays) {
if (!birthdays[team].month[this.month]) {
birthdays.splice(team, 1);
}
}
return birthdays;
},
},
};
This works for the current month (with a few ms or we see the data before the computed) but when we change the month nothing works like birthdays has been modified.
Maybe in my case it is better to stay on a v-if?
CodePudding user response:
splice modifies array in-place (instead of creating new array) so your fiestas
computed is changing this.birthdays
array...
Compute should never have a side-effects. Do this instead:
computed: {
teamsWithBirthdayInCurrentMonth: function () {
return this.birthdays
.filter(team => team.month[this.month])
.map(team => team.name)
},
},