简介
本章记录element ui+vue2中常见的使用技巧和常见问题。
el-table-column中formatter传额外的参数
https://cloud.tencent.com/developer/ask/232934
https://element.eleme.cn/#/zh-CN/component/table#table-column-attributes
el-table-column中的formatter默认回传row, column, cellValue, index
四个参数,如果要传入其他参数,可以用这个方式:
:formatter="(...args) => yourFormatterFun(yourParams, ...args)"
继承el-input-number实现千分位及max-precision效果
新增组件BaseInputNumber
,其index.vue
文件内容如下:
<script>
import ElInputNumber from 'element-ui/packages/input-number';
export default {
extends: ElInputNumber,
name: 'BaseInputNumber',
computed: {
displayValue() {
if (this.userInput !== null) {
return this.userInput;
}
let currentValue = this.currentValue;
if (typeof currentValue === 'number') {
if (this.stepStrictly) {
const stepPrecision = this.getPrecision(this.step);
const precisionFactor = Math.pow(10, stepPrecision);
currentValue = (Math.round(currentValue / this.step) * precisionFactor * this.step) / precisionFactor;
}
if (this.precision !== undefined) {
// 改动1:多余的精度不需要用0补充
// currentValue = currentValue.toFixed(this.precision);
}
}
// 改动2:格式化为千分位
return this.formatterNumber(currentValue);
// return currentValue;
},
},
methods: {
handleFocus(event) {
// 改动3:获得焦点时,恢复真实的值,给用户编辑
this.userInput = this.currentValue;
this.$emit('focus', event);
},
handleBlur(event) {
// 改动4:失去焦点时,为了触发disaplayValue的计算(防止用户不编辑直接失去焦点),这里模仿handleInputChange方法,把userInput设置为null
this.userInput = null;
this.$emit('blur', event);
},
formatterNumber(num) {
if (!num) {
return num;
}
num = num.toString();
let prefix = '';
let suffix = '';
if (num.indexOf('.') === -1) {
prefix = num;
} else {
prefix = num.substring(0, num.indexOf('.'));
suffix = num.substring(num.indexOf('.'));
}
prefix = `${prefix}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `${prefix}${suffix}`;
},
},
};
</script>
– end –