天天看點

16個工程必備的JavaScript代碼片段

作者:_紅領巾

16個工程必備的JavaScript代碼片段

1. 下載下傳一個excel文檔

同時适用于word,ppt等浏覽器不會預設執行預覽的文檔,也可以用于下載下傳後端接口傳回的流資料,見​

​3​

//下載下傳一個連結 
function download(link, name) {
    if(!name){
            name=link.slice(link.lastIndexOf('/') + 1)
    }
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.style.display = 'none'
    eleLink.href = link
    document.body.appendChild(eleLink)
    eleLink.click()
    document.body.removeChild(eleLink)
}
//下載下傳excel
download('http://111.229.14.189/file/1.xlsx')
複制代碼      

2. 在浏覽器中自定義下載下傳一些内容

場景:我想下載下傳一些DOM内容,我想下載下傳一個JSON檔案

/**
 * 浏覽器下載下傳靜态檔案
 * @param {String} name 檔案名
 * @param {String} content 檔案内容
 */
function downloadFile(name, content) {
    if (typeof name == 'undefined') {
        throw new Error('The first parameter name is a must')
    }
    if (typeof content == 'undefined') {
        throw new Error('The second parameter content is a must')
    }
    if (!(content instanceof Blob)) {
        content = new Blob([content])
    }
    const link = URL.createObjectURL(content)
    download(link, name)
}
//下載下傳一個連結
function download(link, name) {
    if (!name) {//如果沒有提供名字,從給的Link中截取最後一坨
        name =  link.slice(link.lastIndexOf('/') + 1)
    }
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.style.display = 'none'
    eleLink.href = link
    document.body.appendChild(eleLink)
    eleLink.click()
    document.body.removeChild(eleLink)
}
複制代碼      

使用方式:

downloadFile('1.txt','lalalallalalla')
downloadFile('1.json',JSON.stringify({name:'hahahha'}))
複制代碼      

3. 下載下傳後端傳回的流

資料是後端以接口的形式傳回的,調用​

​1​

​中的download方法進行下載下傳

download('http://111.229.14.189/gk-api/util/download?file=1.jpg')
 download('http://111.229.14.189/gk-api/util/download?file=1.mp4')

複制代碼      

4. 提供一個圖檔連結,點選下載下傳

圖檔、pdf等檔案,浏覽器會預設執行預覽,不能調用download方法進行下載下傳,需要先把圖檔、pdf等檔案轉成blob,再調用download方法進行下載下傳,轉換的方式是使用axios請求對應的連結

//可以用來下載下傳浏覽器會預設預覽的檔案類型,例如mp4,jpg等
import axios from 'axios'
//提供一個link,完成檔案下載下傳,link可以是  http://xxx.com/xxx.xls
function downloadByLink(link,fileName){
    axios.request({
        url: link,
        responseType: 'blob' //關鍵代碼,讓axios把響應改成blob
    }).then(res => {
 const link=URL.createObjectURL(res.data)
        download(link, fileName)
    })

}
複制代碼      

注意:會有同源政策的限制,需要配置轉發

6 防抖

在一定時間間隔内,多次調用一個方法,隻會執行一次.

這個方法的實作是從Lodash庫中copy的

/**
 *
 * @param {*} func 要進行debouce的函數
 * @param {*} wait 等待時間,預設500ms
 * @param {*} immediate 是否立即執行
 */
export function debounce(func, wait=500, immediate=false) {
    var timeout
    return function() {
        var context = this
        var args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
            // 如果已經執行過,不再執行
            var callNow = !timeout
            timeout = setTimeout(function() {
                timeout = null
            }, wait)
            if (callNow) func.apply(context, args)
        } else {
            timeout = setTimeout(function() {
                func.apply(context, args)
            }, wait)
        }
    }
}
複制代碼      

使用方式:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <input id="input" />
        <script>
            function onInput() {
                console.log('1111')
            }
            const debounceOnInput = debounce(onInput)
            document
                .getElementById('input')
                .addEventListener('input', debounceOnInput) //在Input中輸入,多次調用隻會在調用結束之後,等待500ms觸發一次   
        </script>
    </body>
</html>

複制代碼      

如果第三個參數​

​immediate​

​傳true,則會立即執行一次調用,後續的調用不會在執行,可以自己在代碼中試一下

7 節流

多次調用方法,按照一定的時間間隔執行

這個方法的實作也是從Lodash庫中copy的

/**
 * 節流,多次觸發,間隔時間段執行
 * @param {Function} func
 * @param {Int} wait
 * @param {Object} options
 */
export function throttle(func, wait=500, options) {
    //container.onmousemove = throttle(getUserAction, 1000);
    var timeout, context, args
    var previous = 0
    if (!options) options = {leading:false,trailing:true}

    var later = function() {
        previous = options.leading === false ? 0 : new Date().getTime()
        timeout = null
        func.apply(context, args)
        if (!timeout) context = args = null
    }

    var throttled = function() {
        var now = new Date().getTime()
        if (!previous && options.leading === false) previous = now
        var remaining = wait - (now - previous)
        context = this
        args = arguments
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout)
                timeout = null
            }
            previous = now
            func.apply(context, args)
            if (!timeout) context = args = null
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining)
        }
    }
    return throttled
}
複制代碼      

第三個參數還有點複雜,​

​options​

  • leading,函數在每個等待時延的開始被調用,預設值為false
  • trailing,函數在每個等待時延的結束被調用,預設值是true

可以根據不同的值來設定不同的效果:

  • leading-false,trailing-true:預設情況,即在延時結束後才會調用函數
  • leading-true,trailing-true:在延時開始時就調用,延時結束後也會調用
  • leading-true, trailing-false:隻在延時開始時調用

例子:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <input id="input" />
        <script>
            function onInput() {
                console.log('1111')
            }
            const throttleOnInput = throttle(onInput)
            document
                .getElementById('input')
                .addEventListener('input', throttleOnInput) //在Input中輸入,每隔500ms執行一次代碼
        </script> 
    </body>
</html>

複制代碼      

8. cleanObject

去除對象中value為空(null,undefined,'')的屬性,舉個栗子:

let res=cleanObject({
    name:'',
    pageSize:10,
    page:1
})
console.log("res", res) //輸入{page:1,pageSize:10}   name為空字元串,屬性删掉
複制代碼      

使用場景是:後端清單查詢接口,某個字段前端不傳,後端就不根據那個字段篩選,例如​

​name​

​​不傳的話,就隻根據​

​page​

​​和​

​pageSize​

​篩選,但是前端查詢參數的時候(vue或者react)中,往往會這樣定義

export default{
    data(){
        return {
            query:{
                name:'',
                pageSize:10,
                page:1
            }
        }
    }
}


const [query,setQuery]=useState({name:'',page:1,pageSize:10})
複制代碼      
export const isFalsy = (value) => (value === 0 ? false : !value);

export const isVoid = (value) =>
  value === undefined || value === null || value === "";

export const cleanObject = (object) => {
  // Object.assign({}, object)
  if (!object) {
    return {};
  }
  const result = { ...object };
  Object.keys(result).forEach((key) => {
    const value = result[key];
    if (isVoid(value)) {
      delete result[key];
    }
  });
  return result;
};

複制代碼      
let res=cleanObject({
    name:'',
    pageSize:10,
    page:1
})
console.log("res", res) //輸入{page:1,pageSize:10}
複制代碼      
  • 8個工程必備的JavaScript代碼片段[2]