定義
Vue.js 允許你自定義過濾器,可被用于一些常見的文本格式化。過濾器可以用在兩個地方:雙花括號插值和 v-bind 表達(dá)式 (后者從 2.1.0+ 開始支持)。過濾器應(yīng)該被添加在 JavaScript 表達(dá)式的尾部,
簡單介紹一下過濾器,顧名思義,過濾就是一個數(shù)據(jù)經(jīng)過了這個過濾之后出來另一樣?xùn)|西,可以是從中取得你想要的,或者給那個數(shù)據(jù)添加點(diǎn)什么裝飾,那么過濾器則是過濾的工具。
項(xiàng)目中filter的使用
- 在根目錄創(chuàng)建/filter/index.js,在里面添加全局過濾器,比如一個格式化時間的過濾器
import Vue from 'vue';
// 自定義過濾起
Vue.filter('fomatDate', function (time) {
let date = new Date(time);
let Y = date.getFullYear();
let M = date.getMonth() + 1;
let D = date.getDate();
return `${Y}年-${M}月-${D}日`
})
// 別的過濾器
- 在main.js中導(dǎo)入過濾器
// 導(dǎo)入過濾器
import '@/filter/index';
- 在組件中使用過濾器
:value="item.saleDate | fomatDate" />
<van-list style="margin-top: 10px;">
<van-cell v-for="(item,index) in list"
:key="index"
:title="item.name"
:value="item.saleDate | fomatDate" />
</van-list>