这个函数呢是本身在写基于Vue+ElementUI管理后台时用到的,,下面列出来两种使用方式:javascript
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('&') : '' }
写了一个工具文件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) // ...其余代码...
若是有写的不对或者不合适的地方请多多赐教,毕竟我仍是个前端小菜鸡,happy coding!