1、qs.js库说明
qs是一个url参数转化(parse和stringify)的js库。
https://www.npmjs.com/package/qs
2、使用(以vue文件做示例)
(1)基本语法
<template>
<div>
qs.js
</div>
</template>
<script>
import qs from 'qs'
import _ from 'lodash'
export default {
components: {},
methods: {
qs() {
var obj = qs.parse('a=b&c=d');
//输出true
console.log(_.isEqual(obj, {
a: 'b',
c: 'd'
}))
var str = qs.stringify(obj);
//输出true
console.log(_.isEqual(str, 'a=b&c=d'));
}
},
mounted() {
this.qs();
}
};
</script>
<style scoped>
</style>
(2)忽略符号?
<template>
<div>
qs.js
</div>
</template>
<script>
import qs from 'qs'
import _ from 'lodash'
export default {
components: {},
methods: {
qs() {
//忽略前面的?
var obj = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true });
//输出true
console.log(_.isEqual(obj, {
a: 'b',
c: 'd'
}))
var str = qs.stringify(obj);
//输出true
console.log(_.isEqual(str, 'a=b&c=d'));
}
},
mounted() {
this.qs();
}
};
</script>
<style scoped>
</style>
(3)stringify方法编码
<template>
<div>
qs.js
</div>
</template>
<script>
import qs from 'qs'
import _ from 'lodash'
export default {
components: {},
methods: {
qs() {
//输出a[b]=c
console.log(qs.stringify({
a: {
b: 'c'
}
}, {
encode: false
}))
}
},
mounted() {
this.qs();
}
};
</script>
<style scoped>
</style>
(4)qs 处理数组
<template>
<div>
qs.js
</div>
</template>
<script>
import qs from 'qs'
import _ from 'lodash'
export default {
components: {},
methods: {
qs() {
//输出 'a[0]=b&a[1]=c&a[2]=d'
console.log(qs.stringify({
a: ['b', 'c', 'd']
}))
//输出 a[0]=b&a[1]=c&a[2]=d
console.log(qs.stringify({
a: ['b', 'c', 'd']
}, {
encode: false
}))
//输出 'a=b&a=c&a=d'
console.log(qs.stringify({
a: ['b', 'c', 'd']
}, {
indices: false
}))
}
},
mounted() {
this.qs();
}
};
</script>
<style scoped>
</style>