一、tool.js
1. 小数、整数转千分位
/**
* 小数、整数转千分位(通用)
* @param {number} v 任意数字
* @return {string} 格式化千分位后的数字 例: 22,111
*/
export function formatTh(v) {
if (!_.isNumber(parseFloat(v))) return '-'
if (v.toString().indexOf('.') !== -1) {
// 小数
return v.toString().replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
} else {
// 整数
return v.toString().replace(/(\d)(?=(\d{3})+$)/g, $1 => {
return $1 + ','
})
}
}
2. 内容复制
/**
* 复制文本框内容(仅需提供内容)
* @param {string} cont 需要复制的内容
*/
export function copyEleText(cont) {
const input = document.createElement('input')
document.body.appendChild(input)
input.setAttribute('value', cont)
input.select()
if (document.execCommand('copy')) {
document.execCommand('copy')
console.log('复制成功!')
}
document.body.removeChild(input)
}
二、vue
1. input过滤小数点后两位
<el-input
type="number"
v-model="form.zs"
placeholder="著作总字数(保留两位小数)"
clearable style="width:300px;"
@keyup.native="form.zs = oninput(form.zs)"
>
oninput(val) {
return val ? val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') : null
}
2. 限制输入
<input v-model="license_num" type="text" :change="check_num()" placeholder="请输入">
2.1 限制只能输入数字,英文
check_num() {
this.license_num = this.license_num.replace(/[^\a-\z\A-\Z0-9]/g, '');
}
2.2 限制只能输入正整数
check_num: function(){
var license_num = this.license_num;
license_num = license_num.replace(/[^\d]/g, ''); // 清除“数字”和“.”以外的字符
if (license_num.indexOf('.') < 0 && license_num != '') {
// 以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
license_num = parseInt(license_num);
}
this.license_num = license_num;
}
2.3 限制价格只能输入数字,且最多两个小数
check_price: function(){
var price = '' + this.price;
price = price
.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
.replace('.', '$#$')
.replace(/\./g, '')
.replace('$#$', '.')
.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
if (price.indexOf('.') < 0 && price != '') {
// 以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
price = parseFloat(price);
}
this.price = price;
}