【问题标题】:Computed instead of v-if in v-for计算而不是 v-for 中的 v-if
【发布时间】:2022-01-01 02:38:30
【问题描述】:

我有一个页面显示团队每月的生日。 有两个按钮可让您更改当前月份。

使用 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 上会更好?

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    splice 就地修改数组(而不是创建新数组),因此您的 fiestas 计算值正在改变 this.birthdays 数组...

    计算不应该有副作用。改为这样做:

    computed: {
        teamsWithBirthdayInCurrentMonth: function () {
          return this.birthdays
           .filter(team => team.month[this.month])
           .map(team => team.name)
        },
      },
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 2021-02-21
      • 1970-01-01
      • 2017-07-26
      • 2020-06-28
      • 2021-08-12
      • 1970-01-01
      • 2019-02-27
      • 2018-08-02
      相关资源
      最近更新 更多