七个项目中必备的JavaScript代码片段

开发 前端
本文介绍八个实用的JavaScript代码片段,建议添加到项目中去。

 [[421451]]

1. 下载一个excel文档

同时适用于word,ppt等浏览器不会默认执行预览的文档,也可以用于下载后端接口返回的流数据,见 3

  1. //下载一个链接  
  2. function download(link, name) { 
  3.     if(!name){ 
  4.             name=link.slice(link.lastIndexOf('/') + 1
  5.     } 
  6.     let eleLink = document.createElement('a'
  7.     eleLink.download = name 
  8.     eleLink.style.display = 'none' 
  9.     eleLink.href = link 
  10.     document.body.appendChild(eleLink) 
  11.     eleLink.click() 
  12.     document.body.removeChild(eleLink) 
  13. //下载excel 
  14. download('http://111.229.14.189/file/1.xlsx'
  15. 复制代码 

2. 在浏览器中自定义下载一些内容

场景:我想下载一些DOM内容,我想下载一个JSON文件

  1. /** 
  2.  * 浏览器下载静态文件 
  3.  * @param {String} name 文件名 
  4.  * @param {String} content 文件内容 
  5.  */ 
  6. function downloadFile(name, content) { 
  7.     if (typeof name == 'undefined') { 
  8.         throw new Error('The first parameter name is a must'
  9.     } 
  10.     if (typeof content == 'undefined') { 
  11.         throw new Error('The second parameter content is a must'
  12.     } 
  13.     if (!(content instanceof Blob)) { 
  14.         content = new Blob([content]) 
  15.     } 
  16.     const link = URL.createObjectURL(content) 
  17.     download(link, name) 
  18. //下载一个链接 
  19. function download(link, name) { 
  20.     if (!name) {//如果没有提供名字,从给的Link中截取最后一坨 
  21.         name =  link.slice(link.lastIndexOf('/') + 1
  22.     } 
  23.     let eleLink = document.createElement('a'
  24.     eleLink.download = name 
  25.     eleLink.style.display = 'none' 
  26.     eleLink.href = link 
  27.     document.body.appendChild(eleLink) 
  28.     eleLink.click() 
  29.     document.body.removeChild(eleLink) 
  30. 复制代码 

使用方式:

  1. downloadFile('1.txt','lalalallalalla'
  2. downloadFile('1.json',JSON.stringify({name:'hahahha'})) 
  3. 复制代码 

3. 下载后端返回的流

数据是后端以接口的形式返回的,调用 1 中的download方法进行下载

  1.  download('http://111.229.14.189/gk-api/util/download?file=1.jpg'
  2.  download('http://111.229.14.189/gk-api/util/download?file=1.mp4'
  3.  
  4. 复制代码 

4. 提供一个图片链接,点击下载

图片、pdf等文件,浏览器会默认执行预览,不能调用download方法进行下载,需要先把图片、pdf等文件转成blob,再调用download方法进行下载,转换的方式是使用axios请求对应的链接

  1. //可以用来下载浏览器会默认预览的文件类型,例如mp4,jpg等 
  2. import axios from 'axios' 
  3. //提供一个link,完成文件下载,link可以是  http://xxx.com/xxx.xls 
  4. function downloadByLink(link,fileName){ 
  5.     axios.request({ 
  6.         url: link, 
  7.         responseType: 'blob' //关键代码,让axios把响应改成blob 
  8.     }).then(res => { 
  9.  const link=URL.createObjectURL(res.data) 
  10.         download(link, fileName) 
  11.     }) 
  12.  
  13. 复制代码 

注意:会有同源策略的限制,需要配置转发

5. 防抖

在一定时间间隔内,多次调用一个方法,只会执行一次.

这个方法的实现是从Lodash库中copy的

  1. /** 
  2.  * 
  3.  * @param {*} func 要进行debouce的函数 
  4.  * @param {*} wait 等待时间,默认500ms 
  5.  * @param {*} immediate 是否立即执行 
  6.  */ 
  7. export function debounce(func, wait=500, immediate=false) { 
  8.     var timeout 
  9.     return function() { 
  10.         var context = this 
  11.         var args = arguments 
  12.  
  13.         if (timeout) clearTimeout(timeout) 
  14.         if (immediate) { 
  15.             // 如果已经执行过,不再执行 
  16.             var callNow = !timeout 
  17.             timeout = setTimeout(function() { 
  18.                 timeout = null 
  19.             }, wait) 
  20.             if (callNow) func.apply(context, args) 
  21.         } else { 
  22.             timeout = setTimeout(function() { 
  23.                 func.apply(context, args) 
  24.             }, wait) 
  25.         } 
  26.     } 
  27. 复制代码 

使用方式:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3.     <head> 
  4.         <meta charset="UTF-8" /> 
  5.         <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
  7.         <title>Document</title> 
  8.     </head> 
  9.     <body> 
  10.         <input id="input" /> 
  11.         <script> 
  12.             function onInput() { 
  13.                 console.log('1111'
  14.             } 
  15.             const debounceOnInput = debounce(onInput) 
  16.             document 
  17.                 .getElementById('input'
  18.                 .addEventListener('input', debounceOnInput) //在Input中输入,多次调用只会在调用结束之后,等待500ms触发一次    
  19.         </script> 
  20.     </body> 
  21. </html> 
  22.  
  23. 复制代码 

如果第三个参数 immediate 传true,则会立即执行一次调用,后续的调用不会在执行,可以自己在代码中试一下

6. 节流

多次调用方法,按照一定的时间间隔执行

这个方法的实现也是从Lodash库中copy的

  1. /** 
  2.  * 节流,多次触发,间隔时间段执行 
  3.  * @param {Function} func 
  4.  * @param {Int} wait 
  5.  * @param {Object} options 
  6.  */ 
  7. export function throttle(func, wait=500, options) { 
  8.     //container.onmousemove = throttle(getUserAction, 1000); 
  9.     var timeout, context, args 
  10.     var previous = 0 
  11.     if (!options) options = {leading:false,trailing:true
  12.  
  13.     var later = function() { 
  14.         previous = options.leading === false ? 0 : new Date().getTime() 
  15.         timeout = null 
  16.         func.apply(context, args) 
  17.         if (!timeout) context = args = null 
  18.     } 
  19.  
  20.     var throttled = function() { 
  21.         var now = new Date().getTime() 
  22.         if (!previous && options.leading === false) previous = now 
  23.         var remaining = wait - (now - previous) 
  24.         context = this 
  25.         args = arguments 
  26.         if (remaining <= 0 || remaining > wait) { 
  27.             if (timeout) { 
  28.                 clearTimeout(timeout) 
  29.                 timeout = null 
  30.             } 
  31.             previous = now 
  32.             func.apply(context, args) 
  33.             if (!timeout) context = args = null 
  34.         } else if (!timeout && options.trailing !== false) { 
  35.             timeout = setTimeout(later, remaining) 
  36.         } 
  37.     } 
  38.     return throttled 
  39. 复制代码 

第三个参数还有点复杂, options

  • leading,函数在每个等待时延的开始被调用,默认值为false

  • trailing,函数在每个等待时延的结束被调用,默认值是true

可以根据不同的值来设置不同的效果:

  • leading-false,trailing-true:默认情况,即在延时结束后才会调用函数

  • leading-true,trailing-true:在延时开始时就调用,延时结束后也会调用

  • leading-true, trailing-false:只在延时开始时调用

例子:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3.     <head> 
  4.         <meta charset="UTF-8" /> 
  5.         <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
  7.         <title>Document</title> 
  8.     </head> 
  9.     <body> 
  10.         <input id="input" /> 
  11.         <script> 
  12.             function onInput() { 
  13.                 console.log('1111'
  14.             } 
  15.             const throttleOnInput = throttle(onInput) 
  16.             document 
  17.                 .getElementById('input'
  18.                 .addEventListener('input', throttleOnInput) //在Input中输入,每隔500ms执行一次代码 
  19.         </script>  
  20.     </body> 
  21. </html> 
  22.  
  23. 复制代码 

7. cleanObject

去除对象中value为空(null,undefined,'')的属性,举个栗子:

  1. let res=cleanObject({ 
  2.     name:''
  3.     pageSize:10
  4.     page:1 
  5. }) 
  6. console.log("res", res) //输入{page:1,pageSize:10}   name为空字符串,属性删掉 
  7. 复制代码 

使用场景是:后端列表查询接口,某个字段前端不传,后端就不根据那个字段筛选,例如 name 不传的话,就只根据 page 和 pageSize 筛选,但是前端查询参数的时候(vue或者react)中,往往会这样定义

  1. export default
  2.     data(){ 
  3.         return { 
  4.             query:{ 
  5.                 name:''
  6.                 pageSize:10
  7.                 page:1 
  8.             } 
  9.         } 
  10.     } 
  11.  
  12.  
  13. const [query,setQuery]=useState({name:'',page:1,pageSize:10}) 
  14. 复制代码 

给后端发送数据的时候,要判断某个属性是不是空字符串,然后给后端拼参数,这块逻辑抽离出来就是 cleanObject ,代码实现如下

  1. export const isFalsy = (value) => (value === 0 ? false : !value); 
  2.  
  3. export const isVoid = (value) => 
  4.   value === undefined || value === null || value === ""
  5.  
  6. export const cleanObject = (object) => { 
  7.   // Object.assign({}, object) 
  8.   if (!object) { 
  9.     return {}; 
  10.   } 
  11.   const result = { ...object }; 
  12.   Object.keys(result).forEach((key) => { 
  13.     const value = result[key]; 
  14.     if (isVoid(value)) { 
  15.       delete result[key]; 
  16.     } 
  17.   }); 
  18.   return result; 
  19. }; 
  20.  
  21. 复制代码 
  1. let res=cleanObject({ 
  2.     name:''
  3.     pageSize:10
  4.     page:1 
  5. }) 
  6. console.log("res", res) //输入{page:1,pageSize:10} 
  7. 复制代码 

 

 

责任编辑:张燕妮 来源: 前端技术江湖
相关推荐

2021-10-29 11:05:34

JavaScript代码字符串

2023-03-24 07:30:53

JavaScript项目元框架

2023-01-10 14:54:19

2023-11-13 22:33:47

低代码无代码

2023-09-07 16:28:46

JavaScrip

2023-10-09 14:48:06

2023-10-10 16:16:05

JavaScrip开发

2023-05-22 15:53:06

JavaScrip代码素材

2011-07-11 10:16:07

JavaScript

2024-01-02 18:03:42

编程语言Python

2022-08-16 10:16:53

CIOIT领导者

2024-01-31 12:13:02

JavaScriptSet元素

2024-01-30 18:05:04

IDE编辑器代码

2023-06-16 16:34:25

JavaScripWeb 开发

2024-01-04 16:46:58

JavaScript开发

2023-11-03 16:02:00

JavaScript开发

2023-12-26 14:28:08

JavaScript开发

2023-03-23 15:18:03

JavaScrip代码实践

2022-10-08 23:46:47

JavaScript对象开发

2023-12-07 09:44:29

点赞
收藏

51CTO技术栈公众号