【问题标题】:How to use ternary operator in Vue template with filter?如何在带有过滤器的Vue模板中使用三元运算符?
【发布时间】:2021-04-01 09:57:04
【问题描述】:

我有一个应用可以根据桌面或移动设计设置过滤器,但三元运算符不起作用。

这里是组件调用:

<Metric
    prefix="R$"
    :is-numeric-subvalue="false"
    :is-total="true"
    subvalue="Abril à Maio"
    title="Disponível"
    :value="highlightData.available | defineFilter()"
/>

这是我定义过滤器的方法:

methods: {
  defineFilter () {
    const test = true
    const filter = test ? this.$options.filters.decimal(0) : this.$options.filters.shortedNumber()
    return filter
  }
}

我的过滤器:

filters: {
  decimal: decimalFilter,
  shortedNumber: shortedNumberFilter
}

我收到了警告:

[Vue 警告]:无法解析过滤器:defineFilter

【问题讨论】:

  • 我觉得不错。为什么你认为它不起作用?
  • @NileshPatel 我不知道,不工作 Vue 返回警告“无法解析过滤器:defineFilter”
  • 那是因为它在您的methods 中。将其移至filters
  • @Dan 但是怎么做?将我的方法 defineFilter 移动到过滤器?
  • 是的,过滤器也只是函数

标签: javascript function vue.js vuejs2 vue-component


【解决方案1】:

将您的过滤器移至filters 并删除这两种方法。过滤器将接收数字值作为参数。由于没有this 访问过滤器中的组件,您可以直接使用您的预定义函数:

filters: {
  defineFilter(num) {
    const test = true;
    return test ? decimalFilter(num) : shortedNumberFilter(num);
  }
}

确保您的两个外部函数都准备好接收数字并返回一个值。这是demo

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2020-06-02
    • 2018-12-11
    • 1970-01-01
    • 2014-12-12
    • 2020-03-28
    • 2020-09-17
    • 2012-08-14
    相关资源
    最近更新 更多