5

I'm creating a component that will append query param to current url based on user input. This is the method to change the url.

submitSearch () {
  this.$router.push({query: {search: this.search ? this.search : undefined}})
},

Submitting "john doe" will change the url into http://mysite.test?search=john%20doe

How to make it use + instead? expected url: http://mysite.test?search=john+doe

Christhofer Natalius
  • 2,727
  • 2
  • 30
  • 39

3 Answers3

4

Edit Vue 3 uses '+' by default, so you don't need to do this anymore. But if for some reason you need to use Vue 2, you can use the code below.

=========

Found out that we can override vue-router default querystring parser .

I'm using qs for the parser as shown in 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,
})
Christhofer Natalius
  • 2,727
  • 2
  • 30
  • 39
0

You need to use URI encoding for value parts of query strings, like this:

http://example.com/?param1=(uri-encoded-value)&param2=(uri-encoded-value)&...

You can encode these values using the native function encodeURIComponent.

Example:

const toUrl = (baseUrl = "/", queryObject = {}) => {
  return [
    baseUrl, 
    Object.keys(queryObject).map(k => `${k}=${encodeURIComponent(queryObject[k])}`).join('&')
  ].filter(x => x).join('?')
}
-1

It enters an endless loop redirecting to fullPath over and over. Set a condition that checks for %20 in URL String.

beforeEnter: (to, from, next) => {
if(to.fullPath.includes('%20')) {
  let fullPath = to.fullPath.replace('%20', '+')
  next(fullPath)
} else {
  next()
}
},
Tom Marienfeld
  • 716
  • 3
  • 14