业务场景:
全局封装了一个format的时间日期格式化方法,在当前.vue页面通过filters:{}或者Vue.filter定义过滤器,this为undefined
解决方案:
可以在methods:{ ... }中定义方法,替代filter
<el-table-column prop="syncRowVersion" :label="l('CreationTime')">
<template slot-scope="scope">
<span>{{ formatDate(scope.row.syncRowVersion) }}</span>
</template>
</el-table-column>
formatDate(value) {
return this.$ux.format.dateTime(value);
}
补充:
上面的 this.$ux.format.dateTime(value),是在全局定义的foamat方法并在Vue.prototype中注入
/**
*
* 公用的时间日期、价格等格式化方法
*/
import format from "number-format.js";
import moment from "moment";
export default {
priceFormat: "#,##0.00",
amountFormat: "#,##0.00",
moneyFormat: "#,##0",
costFormat: "#,##0.00",
qtyFromat: "#,##0",
currencyFormat: "#,##0.000000",
weightFormat: "#,##0.0",
volumeFormat: "#,##0.0",
dateFormat: "YYYY-MM-DD",
dateTimeFormat: "YYYY-MM-DD HH:mm:ss",
elementDateFormat: "yyyy-MM-dd",
elementDateTimeFormat: "yyyy-MM-dd HH:mm:ss",
//通用数值格式,用于非price,amount,qty等特殊地方
numberFormat0: "#,##0",
numberFormat2: "#,##0.00",
dateTimebySales(dt, format = "DD/MM/YYYY HH:mm") {
if (!dt) return "";
return moment(dt).format(format);
},
date(dt, format = "YYYY/MM/DD") {
if (!dt) return "";
return moment(dt).format(format);
},
dateTime(dt, format = "YYYY/MM/DD HH:mm:ss") {
if (!dt) return "";
return moment(dt).format(format);
},
price(v) {
return format(v, this.priceFormat);
},
cost(v) {
return format(v, this.costFormat);
},
amount(v) {
return format(v, this.amountFormat);
},
qty(v) {
return format(v, this.qtyFromat);
},
columnFormatter(type) {
let thiz = this;
switch (type) {
case "date":
return function (row, column, cellValue, index) {
return thiz.date(cellValue);
};
case "dateTime":
return function (row, column, cellValue, index) {
return thiz.dateTime(cellValue);
};
case "price":
return function (row, column, cellValue, index) {
return thiz.price(cellValue);
};
case "amount":
return function (row, column, cellValue, index) {
return thiz.amount(cellValue);
};
case "qty":
return function (row, column, cellValue, index) {
return thiz.qty(cellValue);
};
case "cost":
return function (row, column, cellValue, index) {
return thiz.cost(cellValue);
};
}
},
};