位置@/utils/publicMethods.js
/*
* 保留n位小数,默认2位
* 658.146 => 658.14
*/
export const retainDecimals = (number, n = 2) => {
if (isNumber(number)) {
number = (Math.round(number * Math.pow(10, n)) * Math.pow(0.1, n)).toFixed(n);
number = number.toString().split('.');
number = [number[0], number[1] ? number[1].slice(0, n) : ""].join('.');
}
return number;
};
//使用方法
import { retainDecimals } from "../utils/publicMethods"; //根据自己放的位置引入
在methods内写一个函数
methods: {
// 保留数字小数点后两位数
retainDecimalsFun(val, m) {
return setDecimalBit(val, m);
},
}
//在页面上引用
{{ retainDecimalsFun(想要改变的数字, 想要保留的位数:例如:2) }}
位置@/utils/publicMethods.js
//函数防抖
export const debounce = (fn, delay) => {
// 记录上一次的延时器
var timer = null;
var delay = delay || 200;
return function() {
var args = arguments;
var that = this;
// 清除上一次延时器
clearTimeout(timer)
timer = setTimeout(function() {
fn.apply(that, args)
}, delay);
}
}
//函数节流
export const throttle = (func = () => {}, delay = 0) => {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
}
}
//引入组件
import { debounce,throttle } from "../utils/publicMethods";
methods: {
staffDebounceFun: debounce(function () {
在这个位置调用要进行防抖的函数
}, 300), // 间隔的毫秒数
}
//使用方法
<input type="text" @input="staffDebounceFun" />
不需要思考 拿过去就能用 !!!