我正在创建一个组件,该组件将根据用户输入将查询参数附加到当前URL。这是更改网址的方法。
submitSearch () {
this.$router.push({query: {search: this.search ? this.search : undefined}})
},
提交“ john doe”会将网址更改为http://mysite.test?search=john%20doe
如何使其使用+代替?预期的网址:http://mysite.test?search=john+doe
答案 0 :(得分:0)
您需要对查询字符串的值部分使用URI编码,如下所示:
http://example.com/?param1=(uri-encoded-value)¶m2=(uri-encoded-value)& ...
您可以使用本机函数 encodeURIComponent 对这些值进行编码。
示例:
const toUrl = (baseUrl = "/", queryObject = {}) => {
return [
baseUrl,
Object.keys(queryObject).map(k => `${k}=${encodeURIComponent(queryObject[k])}`).join('&')
].filter(x => x).join('?')
}
答案 1 :(得分:0)
发现我们可以override vue-router default querystring parser。
我正在使用qs作为解析器,如this answer from Github
所示const router = new VueRouter({
mode : 'history',
linkActiveClass : 'active',
stringifyQuery : query => {
let result = qs.stringify(query, { format: 'RFC1738' })
return result ? ('?' + result) : ''
},
routes,
})
答案 2 :(得分:-1)
它不断进入无限循环,重定向到fullPath。设置一个条件以检查URL字符串中的%20
。
beforeEnter: (to, from, next) => {
if(to.fullPath.includes('%20')) {
let fullPath = to.fullPath.replace('%20', '+')
next(fullPath)
} else {
next()
}
},