对前端开发的一些小总结

开发前端也有一小日子了。换在以前,我总以为前端不外乎就是写些html和css。再加上一些js。然而,随随着自己学习的积累和工作经验的积累,慢慢发现。原来,前端还有很多是值得我们去学习的。
1、用vue或者是uniapp开发的时候,我们总会运用第三方ui来给页面布局。那么,这就少不了在页面上写上一定的css。

<style lang="less" scoped>
	/*这儿写上你的css 样式*/
</style>

注意在style标签里面的那个scoped,它的意义就是让这里面的css只针对于当前这个页面有效,不会污染其他的页面。这也就是vue里面的一种优势吧。
但需要注意的就是如果加上了 scoped 这个属性。那么,如果你还是按以前的惯例去修改第三方ui(比如 【elementUi 、vantUi】)的样式,那是不能修改的。必须得用深度选择器才能修改。(请看下面的示例代码)

<style lang="less" scoped>
	/*请注意,【/deep/】 是固定写法*/
	/*也就是说,如果需要修改ui里面默认的样式,我们直接在控制台里面找到它的类名*/
	/*然后,在这里面把需要的改了,同时在类名前面加上 /deep/  就完事*/ 
	/deep/ .uni-input-input{
		color: red;
	}
</style>

2、对于vue的监听属性 watch,如果我们要监听的是一个对象,那我们只能是换一种写法,不然无法监听(注意看 watch,里面的 handler 是一个固定写法,这个名字不能随便去更改)。

//如果说你这样写,㜽肯定是报错的
data(){
	return {
		data:{
			category:'',
			name:'',
			amount:null,
		},
	}
},
created() {
	//this.init()
},
watch:{
	'data.amount':{
		handler:function(new,old){
			//有两个参数,第一个是新值,第二个是旧值,跟一般写法的参数是一个样的意思
			console.log(new,old)
		}
	}
}

3、对js时间戳转时间的方法封装(需要注意的是,我这儿的时间戳是毫秒级。所以,如果像php返回的时间戳是秒级的,那就得转换一下了)

    /**
     * [formatDateTime 时间戳转年月日 时分秒]
     * @param  {[type]}  int [时间戳 , 等于空或者等于0的时候为当前时间戳]
     * @param  {[type]}  str [时间格式,格式如下]
     * 时间格式,[y-m-d h:i:s , y-m-d , h:i:s , ymdhis , y-m , m-d , y年m月d日 , y年m月 , m月d日 , y年m月d日 h时i分s秒 , h时i分s秒]
     * 逗号(,)分割返回的是数组,如果还需要做逆运行,那就可以直接做 【...arr】
     * @param  {Boolean} bol [默认为 true ,表示 10以下前面补零]
     * @return {[type]}      [返回对应格式的日期时间格式]
     * 作者话:针对这个方法,大家可以自由去扩展,相信能找到这个博文的,都能看懂,没啥技术含量
     */
    function formatDateTime(int , str, bol = true){
        let date;
        if(int == '' || int == 0){
            date = new Date();
        }else{
            date = new Date(int);
        }
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hours = date.getHours();
        let minutes = date.getMinutes();
        let seconds = date.getSeconds();
        if(bol){
            month       =       month < 10      ?   '0' + month     :   month
            day         =       day < 10        ?   '0' + day       :   day
            hours       =       hours < 10      ?   '0' + hours     :   hours
            minutes     =       minutes < 10    ?   '0' + minutes   :   minutes
            seconds     =       seconds < 10    ?   '0' + seconds   :   seconds
        }
        let strtoLowerCase = str.toLowerCase(); //把传入的转换成小写
        console.log(strtoLowerCase)
        switch(strtoLowerCase){
            case 'y/m/d h:i:s':
                return year + '/' + month + '/' + day  + ' ' + hours + ':' + minutes + ':' + seconds;
            break;
            case 'y-m-d h:i:s':
                return year + '-' + month + '-' + day  + ' ' + hours + ':' + minutes + ':' + seconds;
            break;
            case 'ymdhis':
                return year + '' + month + '' + day  + '' + hours + '' + minutes + '' + seconds;
            break;
            case 'y-m-d':
                return year + '-' + month + '-' + day;
            break;
            case 'y-m':
                return year + '-' + month;
            break;
            case 'm-d':
                return month + '-' + day;
            break;
            case 'ymd':
                return year + '' + month + '' + day;
            break;
            case 'h:i:s':
                return hours + ':' + minutes + ':' + seconds;
            break;
            case 'his':
                return hours + '' + minutes + '' + seconds;
            break;
            case 'y年m月d日 h时i分s秒':
                return year + '年' + month + '月' + day  + '日' + ' ' + hours + '时' + minutes + '分' + seconds + '秒';
            break;
            case 'y年m月d日':
                return year + '年' + month + '月' + day  + '日';
            break;
            case 'h时i分s秒':
                return hours + '时' + minutes + '分' + seconds + '秒';
            break;
            case 'y年m月':
                return year + '年' + month + '月';
            break;
            case 'm月d日':
                return month + '月' + day + '日';
            break;
            case 'y,m,d,h,i,s':
                return [year,month,day,hours,minutes,seconds]
            break;
            case 'y,m,d':
                return [year,month,day]
            break;
        }
    }



//也附上一个时间转时间戳的
let Timestamp = new Date('y-m-d h:i:s').getTime(); //毫秒级,new Date()中如果不传参数,侧默认为当前时间

4、上前图片前对图片进行压缩(图片必须先转成base64)

/**
 * [dealImage 图片压缩]
 * @param  {[type]}   base64   [原图base64的值]
 * @param  {[type]}   w        [需要转换图片的尺寸]
 * @param  {Function} callback [回调函数,用于保存新的图片base64的值]
 * @return {[type]}            [description]
 */
function dealImage(base64, w, callback) {
    var newImage = new Image();
    var quality = 0.4;    //压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute("crossOrigin", 'Anonymous');  //url为外域时需要
    var imgWidth, imgHeight;
    newImage.onload = function () {
        imgWidth = this.width;
        imgHeight = this.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
                canvas.width = w;
                canvas.height = w * imgHeight / imgWidth;
            } else {
                canvas.height = w;
                canvas.width = w * imgWidth / imgHeight;
            }
        } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            quality = 1;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
        var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
        // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定
        // while (base64.length / 1024 > 150) {
        //  quality -= 0.01;
        //  base64 = canvas.toDataURL("image/jpeg", quality);
        // }
        // 防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑
        // while (base64.length / 1024 < 50) {
        //  quality += 0.001;
        //  base64 = canvas.toDataURL("image/jpeg", quality);
        // }
        callback(base64);//必须通过回调函数返回,否则无法及时拿到该值,return拿不到
    }
}

4、js数组对象,相同的键合计的方法

/**
 * [compare 数组对象,相同的键合计的方法]
 * @param  {[type]} arr      [原数组]
 * @param  {[type]} judgeKey [相同的键]
 * @param  {[type]} mergeKey [需要合计的键]
 * @return {[type]}          [返回合计(处理)后的数组]
 * 原文链接 【https://blog.csdn.net/qq_42740797/article/details/119916127】
 */
function compare(arr,judgeKey,mergeKey){
    let result=[];
    arr.forEach(item=>{
        let index=-1;
        result.forEach((m,n)=>{
            if(m[judgeKey]==item[judgeKey]){
                index=n;
            }
        });
        if(index!=-1){
            result[index][mergeKey]+=item[mergeKey];
        }else{
            result.push(item);
        }
    });
    return result;
}

5、将一个大数组折分成多个小数组

/**
 * [formatArr 将一个大数组折分成多个小数组]
 * @param  {[type]} arr         [原数组]
 * @param  {[type]} childrenSum [每个小数组的个数]
 * @return {[type]}             [返回结果集]
 * 例如 原数组
 * [
 * 		{a:1,b:2} , 
 * 		{a:3,b:4} , 
 * 		{a:5,b:6} , 
 * 		{a:7,b:8} , 
 * 		{a:9 , b:10}
 * ]
 *
 *
 *
 * 
 * 我需要折分成 
 * [	[{a:1,b:2} , {a:3,b:4}] , 
 * 		[{a:5,:b:6} , {a:7,b:8}] , 
 * 		[{a:9,b:10}]
 * ]
 *
 */
function formatArr(arr , childrenSum){
	let data = []
    for(var i = 0;i < arr.length;i+=2){
        data.push(arr.slice(i,i+2));
    }
    return data;
}

5、在一苹果机子上,对时间的的转换会有一些小bug

//在一些苹果机子上,new Date('2023-6-9') 它是不能读取到时间的。必须得在不足10的前面补零
new Date('2023-06-09') //这样才能拿到时间
//所以,如果要把时间转换时间戳
//就得这样子弄,把不足10的前面补零
//所以,如果想获取某个时间的时间戳,尽可能用 new Date("2023-06-09 01:02:03") 这种格式
//或者 new Date(2023 , 6 , 3 , 5,30 , 20) 对应 2023年6月3日5时30分20秒
//或者也可以使用 new Date("2023/6/8 5:3:6") 对应 2023年6月8日5时3分6秒
//所以, 坑以后,我决定以后做转换的时候 少用 '-' 如果用了 '-' 不足10 的前面也需要补零
//关于时时的问题 可以参考 https://blog.csdn.net/weixin_44447255/article/details/123424897

6、es6中 fetch 的请求

//表单post提交 (两个任选一个)
function req(){
	fetch('/' , {
		body:'id=1&name=xiaobing&age=18',
		headers:{
			"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
		},
		method:'post',
	})
	.then(res=>res.json())
	.then(res=>{
		console.log(res)
	})
}
function req(){
	var formdata = new FormData();
	formdata.append('id' , 1);
	formdata.append('name' , 'xiaobing'),
	formdata.append('age' , 12)
	fetch('/' , {
		method: 'POST',
		body:formdata
	})
	.then(res=>res.json())
	.then(res=>{
		console.log(res)
	})
}
//这两种方式,在php端,可以直接用 $_POST来接收
//请求载荷
function req(){
	let obj = {
		id:1,
		name:'xiaobing',
		age:18
	}
	fetch('/' , {
		method: 'POST',
		headers: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(obj)
	})
	.then(res=>res.json())
	.then(res=>{
		console.log(res)
	})
}
//而在php端
$res = file_get_contents('php://input');
$data = json_decode($res); //这拿到的就是前端请求的参数
//get请求
//get请求,直接把参数写在请求地址的后面用
/**
 * [toParams 把json对象转换成 用 '&' 符连接的字符串]
 * @param  {[json]} param [json对象]
 * @return {[type]}       [返回 用 '&' 符连接的字符串]
 */
function toParams(param) {
    var result = ""
    for (let name in param) {
        if (typeof param[name] != 'function') {
            result += "&" + name + "=" + encodeURI(param[name]);
        }
    }
    return result.substring(1)
}

function req(){
	let obj = {
		id:1,
		name:'xiaobing',
		age:18
	}
	let params = toParams(obj)
	fetch('/index.php' + '?' + params , {
		method: 'GET',
	})
	.then(res=>res.json())
	.then(res=>{
		console.log(res)
	})
}

7、base64转file对象()

//1,先将base64转换为blob
dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
},
//2,再将blob转换为file
blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
    theBlob.name = fileName;                // 文件名
    return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
},
let blob =  this.dataURLtoBlob(file.content);
let fileName = file.file.name;
//fileName在这儿可以修改名字,正常情况下,file对象是一个主读属性
//所以, 只能通过base64转成file的过程中来修改
let fileObj = this.blobToFile(blob,fileName); //file对象

8、js从一个字符串中提取数字的方法

let num = str.replace(/\D/g, ""); //str为原字符串
num = parseInt(num);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值