Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$router.replace() doesn't update browser query string

The problem is that the query string does not show up in the browser's URL bar.

The code updates the query string in order to keep track of a product configuration.

There are two methods - the first one chooses the model and the second one sets options for that model. Here's the code (the values for the query string are placeholders now):

Methods:

chooseModel (option) {
  this.$router.replace({
    path: this.$route.path,
    query: {m: 'model'},
  })
},
choose (option) {
  if (!this.selectedModel) return
  let opt = {}
  opt[option] = option
  this.$router.push({          // I've tried push and replace
    path: this.$route.path,
    query: Object.assign(this.$route.query, opt),
  })
},

Computed:

selectedModel () {
  return this.$route.query.m
},

When chooseModel is invoked the query string that the browser displays shows up as it should: http://localhost:8080/custom/?m=model. But when choose is invoked the query string that the browser displays remains the same.

FWIW, I have changed the code in chooseModel to set multiple query string values and they all show up. Apparently it is trying to modify that value that causes problems.

Using the debugger I can see that $route.query is correct - it reflects the changes I've made to the query.

I seen the same behavior with both Firefox and Chrome, so it apparently isn't browser-specific.

What do I need to do to get the browser to display the updated query string?

like image 856
bmacnaughton Avatar asked Apr 15 '17 16:04

bmacnaughton


1 Answers

This is my bug but strange behavior nonetheless.

Because a route is immutable Object.assign() is not able to modify it. What is odd is that after my attempt to modify the query string the new route object showed the values I was attempting to set even though the browser didn't display them.

The fix is simple - don't try to modify the route object:

query: Object.assign({}, this.$route.query, opt)

(thanks VCavallo for new link location)

like image 80
bmacnaughton Avatar answered Nov 03 '22 01:11

bmacnaughton