我有一個頁面顯示團隊每個月的生日。帶有兩個按鈕,可讓您更改當前月份。
使用 v-if 的解決方案作業正常,但由于這不是一個好的做法,我嘗試使用計算屬性。
<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 }}
生日的樣本資料:
[
{
"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"
}
]
和我的代碼與計算屬性:
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;
},
},
};
這適用于當前月份(有幾毫秒或者我們在計算之前看到資料)但是當我們更改月份時,沒有什么像生日一樣被修改。
也許就我而言,最好留在 v-if 上?
uj5u.com熱心網友回復:
splice就地修改陣列(而不是創建新陣列),因此您的fiestas計算正在更改this.birthdays陣列...
計算永遠不應該有副作用。改為這樣做:
computed: {
teamsWithBirthdayInCurrentMonth: function () {
return this.birthdays
.filter(team => team.month[this.month])
.map(team => team.name)
},
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364158.html
下一篇:Vue組件由于某種原因更新另一個
