自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

七個項目中必備的JavaScript代碼片段

開發(fā) 前端
本文介紹八個實用的JavaScript代碼片段,建議添加到項目中去。

 [[421451]]

1. 下載一個excel文檔

同時適用于word,ppt等瀏覽器不會默認執(zhí)行預(yù)覽的文檔,也可以用于下載后端接口返回的流數(shù)據(jù),見 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. 復(fù)制代碼 

2. 在瀏覽器中自定義下載一些內(nèi)容

場景:我想下載一些DOM內(nèi)容,我想下載一個JSON文件

  1. /** 
  2.  * 瀏覽器下載靜態(tài)文件 
  3.  * @param {String} name 文件名 
  4.  * @param {String} content 文件內(nèi)容 
  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. 復(fù)制代碼 

使用方式:

  1. downloadFile('1.txt','lalalallalalla'
  2. downloadFile('1.json',JSON.stringify({name:'hahahha'})) 
  3. 復(fù)制代碼 

3. 下載后端返回的流

數(shù)據(jù)是后端以接口的形式返回的,調(diào)用 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. 復(fù)制代碼 

4. 提供一個圖片鏈接,點擊下載

圖片、pdf等文件,瀏覽器會默認執(zhí)行預(yù)覽,不能調(diào)用download方法進行下載,需要先把圖片、pdf等文件轉(zhuǎn)成blob,再調(diào)用download方法進行下載,轉(zhuǎn)換的方式是使用axios請求對應(yīng)的鏈接

  1. //可以用來下載瀏覽器會默認預(yù)覽的文件類型,例如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' //關(guān)鍵代碼,讓axios把響應(yīng)改成blob 
  8.     }).then(res => { 
  9.  const link=URL.createObjectURL(res.data) 
  10.         download(link, fileName) 
  11.     }) 
  12.  
  13. 復(fù)制代碼 

注意:會有同源策略的限制,需要配置轉(zhuǎn)發(fā)

5. 防抖

在一定時間間隔內(nèi),多次調(diào)用一個方法,只會執(zhí)行一次.

這個方法的實現(xiàn)是從Lodash庫中copy的

  1. /** 
  2.  * 
  3.  * @param {*} func 要進行debouce的函數(shù) 
  4.  * @param {*} wait 等待時間,默認500ms 
  5.  * @param {*} immediate 是否立即執(zhí)行 
  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.             // 如果已經(jīng)執(zhí)行過,不再執(zhí)行 
  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. 復(fù)制代碼 

使用方式:

  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中輸入,多次調(diào)用只會在調(diào)用結(jié)束之后,等待500ms觸發(fā)一次    
  19.         </script> 
  20.     </body> 
  21. </html> 
  22.  
  23. 復(fù)制代碼 

如果第三個參數(shù) immediate 傳true,則會立即執(zhí)行一次調(diào)用,后續(xù)的調(diào)用不會在執(zhí)行,可以自己在代碼中試一下

6. 節(jié)流

多次調(diào)用方法,按照一定的時間間隔執(zhí)行

這個方法的實現(xiàn)也是從Lodash庫中copy的

  1. /** 
  2.  * 節(jié)流,多次觸發(fā),間隔時間段執(zhí)行 
  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. 復(fù)制代碼 

第三個參數(shù)還有點復(fù)雜, options

  • leading,函數(shù)在每個等待時延的開始被調(diào)用,默認值為false

  • trailing,函數(shù)在每個等待時延的結(jié)束被調(diào)用,默認值是true

可以根據(jù)不同的值來設(shè)置不同的效果:

  • leading-false,trailing-true:默認情況,即在延時結(jié)束后才會調(diào)用函數(shù)

  • leading-true,trailing-true:在延時開始時就調(diào)用,延時結(jié)束后也會調(diào)用

  • leading-true, trailing-false:只在延時開始時調(diào)用

例子:

  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執(zhí)行一次代碼 
  19.         </script>  
  20.     </body> 
  21. </html> 
  22.  
  23. 復(fù)制代碼 

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. 復(fù)制代碼 

使用場景是:后端列表查詢接口,某個字段前端不傳,后端就不根據(jù)那個字段篩選,例如 name 不傳的話,就只根據(jù) page 和 pageSize 篩選,但是前端查詢參數(shù)的時候(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. 復(fù)制代碼 

給后端發(fā)送數(shù)據(jù)的時候,要判斷某個屬性是不是空字符串,然后給后端拼參數(shù),這塊邏輯抽離出來就是 cleanObject ,代碼實現(xiàn)如下

  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. 復(fù)制代碼 
  1. let res=cleanObject({ 
  2.     name:''
  3.     pageSize:10
  4.     page:1 
  5. }) 
  6. console.log("res", res) //輸入{page:1,pageSize:10} 
  7. 復(fù)制代碼 

 

 

責(zé)任編輯:張燕妮 來源: 前端技術(shù)江湖
相關(guān)推薦

2021-10-29 11:05:34

JavaScript代碼字符串

2024-08-02 17:19:36

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

2025-03-21 08:20:00

數(shù)據(jù)清洗Python編程

2011-07-11 10:16:07

JavaScript

2023-05-22 15:53:06

JavaScrip代碼素材

2024-01-02 18:03:42

編程語言Python

2023-10-09 14:48:06

2023-10-10 16:16:05

JavaScrip開發(fā)

2022-08-16 10:16:53

CIOIT領(lǐng)導(dǎo)者

2024-06-21 11:02:16

2025-02-19 12:00:00

JavaScript代碼數(shù)組方法

2024-01-31 12:13:02

JavaScriptSet元素

2023-06-16 16:34:25

JavaScripWeb 開發(fā)

2023-11-03 16:02:00

JavaScript開發(fā)

2023-12-26 14:28:08

JavaScript開發(fā)

2024-01-04 16:46:58

JavaScript開發(fā)
點贊
收藏

51CTO技術(shù)棧公眾號