JS時間戳轉日期格式

在公共文件夾中封裝

@/utils/validate.js

export function formatDate (date, fmt) {
  if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
  };
  for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
      }
  }
  return fmt;
};

function padLeftZero (str) {
  return ('00' + str).substr(str.length);
};

在模塊中使用

  • 過濾器可以用在兩個地方:雙花括號插值和 v-bind 表達式
    <!-- 數據表格 -->
    <el-table :data="response.data.records" stripe style="width: 100%" border>
      <el-table-column prop="name" label="堆場名稱" width="180"></el-table-column>
      <el-table-column prop="updateDate" label="最新更新" width="180">
        <template slot-scope="scope">
          {{scope.row.updateDate | formatDate}}
        </template>
      </el-table-column>
      <el-table-column prop="goodsType" label="貨種"></el-table-column>
      <el-table-column prop="areaUsed" label="使用面積(平方米)" width="160"></el-table-column>
      <el-table-column prop="areaCapacity" label="總面積(平方米)" width="160"></el-table-column>
      <el-table-column prop="volumn" label="體積(立方米)" width="160"></el-table-column>
      <el-table-column prop="rateRise" label="相比上日"></el-table-column>
      <el-table-column prop="rateUsage" label="使用負荷" width="180">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.rateUsage * 100"></el-progress>
        </template>
      </el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button @click="openDetail" type="primary" round>詳情</el-button>
        </template>
      </el-table-column>
    </el-table>
  • 引入封裝好的js文件
  • 在組件中定義本地的過濾器
<script>
	import api from "@/api/modules/space";
	import { formatDate } from '../../utils/validate.js';
	export default {
		filters: {
		    formatDate(time) {
		        var date = new Date(time);
		        return formatDate(date, 'yyyy-MM-dd hh:mm');
		    }
		  },
	    methods: {
			async getStorageYard() {
		      this.response = await api.getStorageYard(this.search);
		      console.log(this.response);
		    }
	    },
	    mounted() {
	      this.getStorageYard();
	    }
    }
</script>

頁面渲染結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章