【问题标题】:Vue: Switch between result arrays with checkboxVue:使用复选框在结果数组之间切换
【发布时间】:2021-08-12 23:35:45
【问题描述】:

我有一个计算属性,它将数据“V”带回一个选择下拉列表中,并以逗号分隔并对其进行排序。一切都很好。

我还有一个复选框,允许用户显示日期已过的记录。此信息通过选中复选框来显示。这也行得通。

所以我要做的是根据是否选中复选框在两个不同的功能之间切换。

所以我想说的是(虽然语法不正确)是这样的:

if (checkboxX === true)  const metaVFees = this.resultfilteredResults
else (checkboxX === false)  const metaVFees = this.results

并将其处理到此计算属性中。请问有人可以帮忙吗?

uniqueSubjects() {
  const metaVFees = this.resultfilteredResults // <--- This should switch
    .filter((result) => result.metaData && result.metaData.V)
    .map((item) => item.metaData.V)
    .filter((subject, i, arr) => arr.indexOf(subject) === i);
  // Split multiple subjects in strings and store in an array
  let subjects = [];
  metaVFees.forEach((item) => {
    const splitArr = item.split(", ");
    subjects = subjects.concat(splitArr);
  });
  return subjects
    .sort()
    .filter((subjects, i, arr) => arr.indexOf(subjects) === i);
},

【问题讨论】:

    标签: vue.js conditional-statements computed-properties


    【解决方案1】:

    有几种方法可以解决这个问题,但最简单的可能是 JavaScript 的 Conditional (Ternary) Operator

    [conditional] ? [expression if true] : [expression if false]

    在你的情况下看起来像这样:

    this.metaVFees ? this.resultfilteredResults : this.results

    这个语句说如果this.metaVFees 为真,“执行”this.resultfilteredResults,如果为假,则this.results(我说执行,因为你可以使用完整的语句/表达式运算符,但我们这里只需要单个值)。

    我们可以将三元表达式直接放入您的计算属性中 (为了清楚起见,我喜欢括号,但实际上并不是必需的,因为这里后面有一个换行符):

    ...
    const metaVFees = (this.metaVFees ? this.resultfilteredResults : this.results)
        .filter((result) => result.metaData && result.metaData.V)
        .map((item) => item.metaData.V)
        .filter((subject, i, arr) => arr.indexOf(subject) === i);
    ...
    

    这是一个简短的 sn-p,展示了这种表达方式:

    new Vue({
      el: '#app',
      data() { return {
        flag: false,
        values1: [1, 2, 3, 4, 5],
        values2: [6, 7, 8, 9, 10],
      }},
      computed: {
        ternaryComputed() {
          return this.flag ? this.values1 : this.values2
            .filter(num => num % 2 == 0); // Filter out odd numbers
        },
      },
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
    <div id="app">
      <div>{{ `Computed: ${ternaryComputed}` }}</div><br>
      <button @click="flag = !flag">Swap Array</button><br><br>
      <div>{{`(this.flag ? this.values1 : this.values2) = [${(this.flag ? this.values1 : this.values2)}]`}}</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2023-01-03
      • 2023-03-29
      相关资源
      最近更新 更多