Vue element el-table-column中對日期進行格式化方式(全局過濾器)
element el-table-column中對日期進行格式化
1、安裝時間格式化插件
npm install vue-moment --save
2、在main.js中引用
import moment from 'moment'
?
Vue.use(require('vue-moment'));
Vue.prototype.moment = moment3、在main.js中加入日期格式化的過濾器,其中dateYMDHMSFormat為方法名稱
Vue.filter('dateYMDHMSFormat',function(dateStr,pattern='YYYY-MM-DD HH:mm:ss'){
? return moment(dateStr).format(pattern);
})4、普通使用方法,date為參數(shù)名,后面dateYMDHMSFormat為方法名稱
<p>{{date | dateYMDHMSFormat}}</p>但是,在table中需要添加插槽
不加格式化寫法:
<el-table-column prop="date" label="時間"></el-table-column>
加入格式化寫法:
<el-table-column prop="date" label="時間">
? ? <template slot-scope="scope">{{scope.row.date| dateYMDHMSFormat}}</template>
</el-table-column>el-table格式化el-table-column內(nèi)容
遇到一個需求,一個循環(huán)展示的table中的某項,或者某幾項需要格式化。對于格式化的方法,主要有template scope、formatter;
template scope 、v-if判斷
<el-table-column prop="cyxb" label="性別">
<template slot-scope="scope">
<span v-if="scope.row.cyxb == 0">男</span>
<span v-if="scope.row.cyxb == 1">女</span>
</template>
</el-table-column>

利用formatter、slot屬性
查看幫助文檔

<el-table-column prop="xb1" label="成員性別1" width="120" :formatter="Formatter">
Formatter(row, column){
if(row.xb == 0){
return "男"
}else if(row.xb == 1){
return "女"
}
}

但這些對我當前的情況,并不適用
所以,后來發(fā)現(xiàn)一個好方法。將兩種方法結(jié)合起來,使用slot,自定義 formatter.(自定義)靈活應(yīng)用就好啦??
<el-table-column
v-for="column in cbdksTableColumns"
:prop="column.field"
:label="column.label"
sortable="custom"
:key="column.field"
min-width="200"
>
<template slot-scope="scope">
<div v-if="column.field == 'cyxb'">
<span v-html="xbFormatter(scope.row.cyxb, scope.column.property)"></span>
//將表格數(shù)據(jù)格式化后,再用 template + v-html 展示出來
</div>
//<div v-else-if="column.field == 'qqfs'">中間還可以加好多判斷,從此針對某列的值進行格式化。
<div v-else>
{{ scope.row[scope.column.property] }}//千萬不要忘啦?。?!
</div>
</template>
</el-table-column>
//之前的代碼取數(shù)據(jù)比較復(fù)雜,簡化代碼,便于理解。
xbFormatter(value, row) {
//性別
let cyxbvalue = value;
if (cyxbvalue == null || cyxbvalue == "" || cyxbvalue == undefined) {
return cyxbvalue;
} else {
let dycyxb = this.xbOptions.filter((item) => item.value === cyxbvalue);//filter過濾方法(看自己的情況、需求)
return dycyxb[0].label;//rerun的內(nèi)容即為要在表格中顯示的內(nèi)容
}
},
此處xbOptions是調(diào)用后臺接口返回的數(shù)據(jù),組織結(jié)構(gòu)為
this.xbOptions.push({ label: mj.mjmc, value: mj.mjz });返回結(jié)果

當然xbOptions也可直接在data中靜態(tài)定義。也可不定義,直接在return返回想要顯示的內(nèi)容也可。
當然這個方法中,不僅僅if語句,自行判斷的語句都在這,判斷完返回結(jié)果就歐克了。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù))
這篇文章主要介紹了vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
Vue點擊在彈窗外部實現(xiàn)一鍵關(guān)閉的示例代碼
在Vue應(yīng)用中,彈窗是一個常見的交互元素,有時我們可能希望用戶點擊彈窗外部時,彈窗能夠自動關(guān)閉,本文主要介紹了Vue點擊在彈窗外部實現(xiàn)一鍵關(guān)閉的示例代碼,感興趣的可以了解一下2024-06-06
vue-cli是什么及創(chuàng)建vue-cli項目的方法
vue-cli是 vue 官方提供的、快速生成 vue 工程化項目的工具,支持創(chuàng)建vue2和vue3的項目,本文給大家詳細講解vue-cli是什么及創(chuàng)建vue-cli項目的方法,感興趣的朋友跟隨小編一起看看吧2023-04-04

