在 Vue 2.0 中重建被移除的 filters
在 1.0 版本中的 filters 實在是讓我愛不釋手,簡易的過濾方式,支援字串篩選、金額數字格式等,但是這麼好用的功能卻在 2.0 中被移除了,以下為 Vue.js 作者在 Github 的相關討論串中回應的內容:
I was also one of the big proponents for removing filters in Vue 2.0.
The problem with filters for beginners to Vue
A big part of the reason I was in favor of deprecating filters was actually for beginners. When working with students, this is a conversation that’s come up more than once:
- Student: “So a filter is basically a function?”
- Mentor: “Yes!”
- Student: “OK, so can I use it normally with function parentheses?”
- Mentor: “Well, no. It’s a special kind of function.”
- Student: “Can I use it in other places? Like in a computed value?”
- Mentor: “No, you can only use it in templates and only with the special pipe syntax.”
- Student: “… why?”
作者認為我們應該要教會學生怎麼實作這些功能,而不是像魔術一般的實現,這可能會導致一些初學者誤認為也能夠在其他的地方簡單的使用這些 magic function 來輕鬆的達到想要的功能。
不過沒關係,就算這些好用的 filters 被移除,我們還是有辦法一步一步重建回來,就拿 currency 這個過濾器來說好了,在 1.0 的版本中,我們能夠很快速的呈現金額的分位數及貨幣符號,例如 10000000 可以轉化為 $10,000,000 ,這樣比起一長串的數字是不是好讀多了呢?尤其是在涉及到大量點數或是金額的網站,接下來我們會一步一步將這個超好用的 filter 裝回來,讓你的數字也可以清楚地被呈現。
首先我們先建立一個統籌所有過濾器的 js 檔案
建立完之後我們建立一個 Vue instance
最後我們就可以開心的使用 currency 來加上分位符號啦!相信還有其他方法能夠做到,例如用 Vue.filters 來註冊並在全局引用,上述的方法只是簡單的利用 methods 來還原這個效果而已,如果有其他更好的建立方法也希望交流一下唷!