<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          16個項目中必備的JavaScript代碼片段(建議添加到項目中)

          共 14807字,需瀏覽 30分鐘

           ·

          2021-09-05 00:39

          點擊上方關(guān)注 前端技術(shù)江湖,一起學(xué)習(xí),天天進(jìn)步


          1. 下載一個excel文檔

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

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

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

          /**
           * 瀏覽器下載靜態(tài)文件
           * @param {String} name 文件名
           * @param {String} content 文件內(nèi)容
           */

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

          使用方式:

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

          3. 下載后端返回的流

          數(shù)據(jù)是后端以接口的形式返回的,調(diào)用1中的download方法進(jìn)行下載

           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')

          復(fù)制代碼

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

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


          //可以用來下載瀏覽器會默認(rèn)預(yù)覽的文件類型,例如mp4,jpg等
          import axios from 'axios'
          //提供一個link,完成文件下載,link可以是  http://xxx.com/xxx.xls
          function downloadByLink(link,fileName){
              axios.request({
                  url: link,
                  responseType'blob' //關(guān)鍵代碼,讓axios把響應(yīng)改成blob
              }).then(res => {
           const link=URL.createObjectURL(res.data)
                  download(link, fileName)
              })

          }
          復(fù)制代碼

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

          6 防抖

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

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

          /**
           *
           * @param {*} func 要進(jìn)行debouce的函數(shù)
           * @param {*} wait 等待時間,默認(rèn)500ms
           * @param {*} immediate 是否立即執(zhí)行
           */

          export function debounce(func, wait=500, immediate=false{
              var timeout
              return function() {
                  var context = this
                  var args = arguments

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

          使用方式:

          <!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中輸入,多次調(diào)用只會在調(diào)用結(jié)束之后,等待500ms觸發(fā)一次   
                  </script>

              </body>
          </html>


          復(fù)制代碼

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

          7 節(jié)流

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

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

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

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

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

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

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

          例子:

          <!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執(zhí)行一次代碼
                  </script>
           
              </body>
          </html>


          復(fù)制代碼

          8. cleanObject

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

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

          使用場景是:后端列表查詢接口,某個字段前端不傳,后端就不根據(jù)那個字段篩選,例如name不傳的話,就只根據(jù)pagepageSize篩選,但是前端查詢參數(shù)的時候(vue或者react)中,往往會這樣定義


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


          const [query,setQuery]=useState({name:'',page:1,pageSize:10})
          復(fù)制代碼

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

          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;
          };

          復(fù)制代碼
          let res=cleanObject({
              name:'',
              pageSize:10,
              page:1
          })
          console.log("res", res) //輸入{page:1,pageSize:10}
          復(fù)制代碼

          剩下的8個在這里:

          • 8個工程必備的JavaScript代碼片段[2]

          以上代碼片段都經(jīng)過項目檢測,可以放心使用在項目中。

          參考資料

          [1]

          https://juejin.cn/post/6987962113788493831: https://juejin.cn/post/6987962113788493831

          [2]

          https://juejin.cn/post/6999391770672889893: https://juejin.cn/post/6999391770672889893




          關(guān)于本文

          作者:_紅領(lǐng)巾

          https://juejin.cn/post/7000919400249294862

          The End

          歡迎自薦投稿到《前端技術(shù)江湖》,如果你覺得這篇內(nèi)容對你挺有啟發(fā),記得點個 「在看」


          點個『在看』支持下 

          瀏覽 37
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲午夜福利 | 欧美精品成人一区二区三区四区 | 成人91av | 爱爱视频不卡免费观看 | 操逼免费 |