Removing query string parameter from Url

Viewed 23004

Coming from AngularJS I thought this would be easy enough in Vue.js 2 as well. But it seems this is difficult by design in Vue.

In AngularJS I can do this $location.search('my_param', null); which will effectively turn https://mydomain.io/#/?my_param=872136 into https://mydomain.io/#/.

In Vue I have tried this.$router.replace('my_param',null);, but it will only do https://mydomain.io/#/?my_param=872136 -> https://mydomain.io/#/my_param, leaving the empty my_param.

Isn´t there anyway in Vuejs2 to remove the query params from the Url? Should I resort to plain JS to achieve this?

3 Answers

In the case that you have multiple query parameters the correct way to remove one of them would be:

const query = Object.assign({}, this.$route.query);
delete query.my_param;
this.$router.replace({ query });

@DaveIdito's answer given in a comment above has been valuable to me several times. Adding it as an answer in order to bring proper attention to it.

To only remove all of the the query params without loading again or changing history, use:

this.$router.replace({'query': null});
Related