分享一個好用的函數吧,將js中的對象轉成url參數


JavaScript&jQuery獲取url參數方法

這個函數呢是自己在寫基於Vue+ElementUI管理后台時用到的,,下面列出來兩種使用方式:

最普通的,封裝一個js函數


 /**
   * 對象轉url參數
   * @param {*} data
   * @param {*} isPrefix
   */
 queryParams (data, isPrefix) {
    isPrefix = isPrefix ? isPrefix : false
    let prefix = isPrefix ? '?' : ''
    let _result = []
    for (let key in data) {
      let value = data[key]
      // 去掉為空的參數
      if (['', undefined, null].includes(value)) {
        continue
      }
      if (value.constructor === Array) {
        value.forEach(_value => {
          _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
        })
      } else {
        _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
      }
    }

    return _result.length ? prefix + _result.join('&') : ''
  }

在Vue組件化開發時,我是這樣寫的

寫了一個工具文件 utils.js,將其作為工具包引入Vue的 main.js,並將其附給 Vue原型,這樣在每個組件中就可以使用 this.$utils來使用里面的一些工具函數了

utils.js文件


const utils = {
  /**
   * 對象轉url參數
   * @param {*} data
   * @param {*} isPrefix
   */
  queryParams (data, isPrefix = false) {
    let prefix = isPrefix ? '?' : ''
    let _result = []
    for (let key in data) {
      let value = data[key]
      // 去掉為空的參數
      if (['', undefined, null].includes(value)) {
        continue
      }
      if (value.constructor === Array) {
        value.forEach(_value => {
          _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
        })
      } else {
        _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
      }
    }

    return _result.length ? prefix + _result.join('&') : ''
  },

  // ....其他函數....

}

export default utils

main.js文件


import Vue from 'vue'
import App from './App.vue'
import utils from '@/utils/utils'

// ...其他代碼...

Vue.prototype.$utils = utils

// ...其他代碼...

在使用的時候可以這樣寫

// ....其他代碼

this.$utils.queryParams(this.params)

// ...其他代碼...


<blockquote>如果有寫的不對或者不合適的地方請多多賜教,畢竟我還是個前端小菜雞,happy coding!</blockquote>

來源:https://segmentfault.com/a/1190000016416023


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM