欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue實(shí)現(xiàn)的封裝全局filter并統(tǒng)一管理操作示例

 更新時(shí)間:2020年02月02日 10:01:35   作者:不想寫代碼的碼農(nóng)  
這篇文章主要介紹了vue實(shí)現(xiàn)的封裝全局filter并統(tǒng)一管理操作,結(jié)合實(shí)例形式詳細(xì)分析了vue封裝全局filter及相關(guān)使用技巧,需要的朋友可以參考下

本文實(shí)例講述了vue實(shí)現(xiàn)的封裝全局filter并統(tǒng)一管理操作。分享給大家供大家參考,具體如下:

在前后端分離的項(xiàng)目中,經(jīng)常會有后臺返回的數(shù)據(jù)需要進(jìn)過處理才能顯示到頁面上的場景。

使用最多的場景就是日期和時(shí)間的處理,后臺一般返回的都是時(shí)間戳,那么我們就要對時(shí)間戳進(jìn)行處理。

下面就拿封裝全局的處理日期和時(shí)間的 filter 來展示如何 vue 如何封裝全局 filter 并統(tǒng)一處理。

src 目錄下新建 filters 目錄用來專門存放全局過濾器,如果項(xiàng)目的過濾器過多,那么就要按類型分類。

我司的項(xiàng)目需要前臺處理的數(shù)據(jù)不是太多,那么就在 filters 目錄下新建一個 index.js 來存放所有的過濾器就足夠了。

index.js 代碼如下:

/*
  日期處理
    time:源時(shí)間戳
    type:要處理的格式 默認(rèn) xxxx年xx月xx日
      /: xxxx/xx/xx
      .: xxxx.xx.xx
      -: xxxx-xx-xx
 */
export const normalDate = (time,type) => {
  if (time) {
    var date = new Date();
    date.setTime(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) * 1 : date.getMonth() + 1;
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    if(type == '-'){
      return year + '-' + month + '-' + day;
    }else if(type == '/'){
      return year + '/' + month + '/' + day;
    }else if(type == '.'){
      return year + '.' + month + '.' + day;
    }else{
      return year + '年' + month + '月' + day + '日';
    }
  }
}
/*
  時(shí)間處理
    time:源時(shí)間戳
    type:要處理的格式 默認(rèn) xxxx年xx月xx日 xx:xx:xx
      /: xxxx/xx/xx xx:xx:xx
      .: xxxx.xx.xx xx:xx:xx
      -: xxxx-xx-xx xx:xx:xx
 */
export const normalTime = (time,type) => {
  if (time) {
    var date = new Date();
    date.setTime(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) * 1 : date.getMonth() + 1;
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    if(type == '-'){
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }else if(type == '/'){
      return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }else if(type == '.'){
      return year + '.' + month + '.' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }else{
      return year + '年' + month + '月' + day + '日' + ' ' + hours + ':' + minutes + ':' + seconds;
    }
  }
}

然后在 main.js 中引入注冊即可使用:

import * as filters from './filters'
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]));

在頁面中使用:

<p>{{time | normalDate('/')}}</p> //這樣時(shí)間戳就會轉(zhuǎn)化為xxxx/xx/xx的格式

希望本文所述對大家vue.js程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論