Viggo Lundén
Viggo Lundén

Reputation: 788

Ternary operator and Vue filters

I've encountered a weird behavior in Vue. See the following vue.html code:

<label :text= 
    "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`">
</label>

This won't compile, and Vue throws the following warning:

[Vue warn]: Property or method "myFilter" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in Root)

However, when I'm not using a the ternary operator:

<label :text=
    "($props.information.primary || $props.information.secondary) | myFilter">
</label>

It compiles just fine, and myFilter is found. myFilter is declared in boot.ts. Why does it throw in the first example? There is no difference in scope.

Upvotes: 2

Views: 2190

Answers (3)

Carlos Ceballos
Carlos Ceballos

Reputation: 1

Works for me:

:text="${props.information.primary ? props.information.primary : myFilter}"

Other option is:

:text="${props.information ? props.information.primary ? props.information.secondary : myFilter}"

Upvotes: 0

Pulkit Aggarwal
Pulkit Aggarwal

Reputation: 643

The expression syntax is defined as (JavaScript expression) + (prop | filters). Filters can only be appended to valid JavaScript - bringing in filters into JavaScript is not going to happen.

You can already use $options.filters.myFilter(prop) in JavaScript expressions.

Please refer here: https://github.com/vuejs/vue/issues/5449#issuecomment-294337677

Upvotes: 3

Roy J
Roy J

Reputation: 43881

A single vertical bar is the bitwise-or operator. Vue has done some special parsing to interpret it as "pipe to filter" in a binding, but (I surmise) only as a series of one or more occurrences at the end of the binding expression, not in the middle, as is the case with your ternary usage.

Upvotes: 3

Related Questions