很多時候我們從後臺拿到的數據格式並不是我們想要的,比如時間,一般後臺給的是時間戳,前端需要轉化爲類似YYYY-MM-NN的形式,如果不是直接渲染數據,還是能夠使用moment包去轉化,如果是像在表格中這種寫法還比較簡單,能夠對數據直接操作
{title: "更新時間", align: "center",key: "updateTime",
render: (h, params) => {
return h('div',moment.unix(params.row.Time/1000).format("YYYY-MM-DD HH:mm:ss"));
},
},
而像需要直接渲染的可能就需要我們遍歷列表去一個一個修改,比較麻煩,這時候就可以使用過濾器。
過濾器有兩種,一種是全局過濾器,可以在任何一個組件內都可以使用。另一種則是組件內部的過濾器,註冊組件內部過濾器則只能在當前組件內使用。
全局過濾器
import Vue from 'vue';
Vue.filter('formatTime', function (val) {
const date = new Date(val);
const year = date.getFullYear();
const month = date.getMonth() > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`;
const day = date.getDate() > 9 ? date.getDate() + 1 : `0${date.getDate() + 1}`;
const hour = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
return `${year}-${month}-${day} ${hour} : ${minutes} : ${seconds}`;
});
局部過濾器
export default {
name: 'FilterDemo',
/* 局部過濾器 */
filters: {
/* 格式化時間戳 */
formatTime (val) {
const date = new Date(val);
const year = date.getFullYear();
const month = date.getMonth() > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`;
const day = date.getDate() > 9 ? date.getDate() + 1 : `0${date.getDate() + 1}`;
const hour = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
return `${year}-${month}-${day} ${hour} : ${minutes} : ${seconds}`;
}
},
data () {
return {
}
}
}
過濾器的使用
<template>
<div>{{ time | formatTime }}</div>
<div v-bind:id="time | formatTime"></div>
</template>