轉載於簡書
鏈接:http://www.jianshu.com/p/29b7eaabd1ba
問題
2.0 filters only work in mustache tags and v-bind.
Vue2.0 不再支持在 v-html
中使用過濾器,比如在 1.0 中是這樣使用的:
{{{ option.title | highlight }}}
然而,現在不能使用了,Vue2.0 的過濾器現在只能應用在 {{ }}
和 v-bind
中。
然而,嫌麻煩,還想使用怎么辦?
解決方法
- 使用全局方法
- 使用 computed 屬性
- 使用 $options.filters
使用全局方法
put your
highlight
into methods, andv-html="highlight(option.title)"
可以在 Vue 上定義全局方法:
Vue.prototype.highlight= function (sTitle) {
// to do
};
然后所有組件上都可以直接用這個方法了:
v-html="highlight(option.title)"
使用 computed 屬性
- 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.
當然,可以使用計算屬性 computed
,返回原生 html
給 v-html
即可。
使用 $options.filters
You can use $options.filters
v-html="$options.filters.highlight(option.title)".
這個方式在文檔中並沒有說明,但是這也是可靠的方法。
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