Vue: v-html does not work with filters

Created on 30 Nov 2016  ·  11Comments  ·  Source: vuejs/vue

Vue.js version

2.1.3

Reproduction Link

https://jsfiddle.net/peterkorgaard/t1Lxnwoq/16/

Steps to reproduce

In my fiddle I have added a filter and two uses of it. One with v-html and one with mustache interpolations. The first one (v-html) returns 0 and throws an error in the console. The latter prints the html code produced by the filter - but it is of course not rendered as html, because this is not supported with mustache interpolations. The example with v-html, on the other hand, should render as html.

What is Expected?

Rendered html

What is actually happening?

Vue does not recognize the filter when using v-html. For the record. The same thing happens when using v-text.

Most helpful comment

You can use $options.filters :

v-html="$options.filters.highlight(option.title, searchTerm)".

All 11 comments

2.0 filters only work in mustache tags and v-bind.

How to implement a highlight that was simple in v.1:

{{{ option.title | highlight(searchTerm) }}}

with filter highlight that wrapped found text in spans?

@SlyNet put your highlight into methods, and v-html="highlight(option.title, searchTerm)".

What if I have a filter that outputs HTML? Do I have to use a computed property or is there a better way?

Computed properties are the best way. You get automatic caching.

You can use $options.filters :

v-html="$options.filters.highlight(option.title, searchTerm)".

Fridus - works indeed! But looks like undocumented private API

@Fridus this works fine ,thx

@Fridus You can safely rely on that: $options are the options passed to the Vue constructor when creating a vm (so any component or new Vue). From that point on is just javascript 🙂

@Fridus I really like this way to do it. No nasty mustache tags needed for this! Thanks!

The solution "$options.filters.highlight(option.title, searchTerm)" is ugly, the pipe,
as in <p v-html="message | toHTML"></p>,
is need to be orthogonal... Seems a LANGUAGE DESIGN BUG.

Was this page helpful?
0 / 5 - 0 ratings