Igoohd
Igoohd

Reputation: 166

How to use ternary operator in Vue template with filter?

I have an app to set a filter depending on desktop or mobile design, but the ternary operator doesn't work.

Here is the component call:

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

Here is my method to define the filter:

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

My filters:

filters: {
  decimal: decimalFilter,
  shortedNumber: shortedNumberFilter
}

I received the warning:

[Vue warn]: Failed to resolve filter: defineFilter

Upvotes: 3

Views: 1120

Answers (1)

Dan
Dan

Reputation: 63059

Move your filter to filters and remove both methods. The filter will receive the number value as an argument. Since there is no this access to the component in a filter, you can use your predefined functions directly:

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

Make sure that both of your external functions are prepared to receive the number and return a value. Here's a demo

Upvotes: 2

Related Questions