這個函數呢是自己在寫基於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