vue項目中 指令 v-html 中使用過濾器filters功能



轉載於簡書
鏈接: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, and v-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,返回原生 htmlv-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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM