Home > Article > Web Front-end > Introduction to the function that can convert objects in js into url parameters (code example)
This article brings you an introduction to the function that can convert objects in js into url parameters (code examples)). It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.
This function is used when I write a management background based on Vue ElementUI. There are two ways to use it:
js
Function/** * 对象转url参数 * @param {*} data * @param {*} isPrefix */ urlencode (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('&') : '' }
utils.js
Fileconst utils = { /** * 对象转url参数 * @param {*} data * @param {*} isPrefix */ urlencode (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
Fileimport Vue from 'vue' import App from './App.vue' import utils from '@/utils/utils' // ...其他代码... Vue.prototype.$utils = utils // ...其他代码...
// ....其他代码 this.$utils.urlencode(this.params) // ...其他代码...
The above is the detailed content of Introduction to the function that can convert objects in js into url parameters (code example). For more information, please follow other related articles on the PHP Chinese website!