Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VUEJS-How to remove parameter from url

I have multiple parameters in url. I am adding new parameter in url with following code:

this.$router.push({query: Object.assign({}, this.$route.query, {cities: '1,45'})});

But when I unselect cities, still it keep last id with cities param in url:

projects#/?cities=2189673&gender=male&range=100

Actually I want to remove cities parameter only. How can I do?

Further how to get all params of url to post to php?

like image 358
ghulamjafar Avatar asked Feb 09 '18 07:02

ghulamjafar


1 Answers

I know this isn't the best solution, since it relays on a third-party library.

Lodash is a suite of functions to manage collections of data.

If you want to remove the 's' query Param from the URL, using Lodash, you can do:

// remove a param from $route.query
var newRouteQuery = _.omit(this.$route.query, 's');
this.$router.replace( { query: newRouteQuery } );

The _.omit() Lodash's function takes as first argument an Object, and returns the same object but without the items who's keys are listed in the second argument. Since, in this case, we only pass a string as the second argument (the string 's'), the function will only omit one index of the object.

A vanilla-javascript implementation of this function would be something like this (note: ie8 doesn't support this, keep it in mind if you're not using webpack).

// Omit 's' from vue router query params
var newRouteQuery = {};
Object.keys(this.$route.query).forEach(function(key){
    if (key != 's')
        newRouteQuery[key] = this.$route.query[key];
});

To pass all of this parameters to PHP, you basically need an Ajax API to send requests. You can pass the contents of this.$route.query to the server either via POST, GET or any other method.

Using the Fetch API (which doesn't require any extra library and has almost complete browser support), you can do something like this:

return fetch('/process.php', {
    method: 'POST',
    cache: 'no-cache', // don't cache the response
    credentials: 'omit', // don't send cookies
    body: JSON.stringify(this.$route.query)
})
.then(function(response){
    // ...

In this case I'm sending a POST request with the data as a JSON string in the body of the request. There are different ways to send data and different types of requests. You should investigate the best method for your PHP enviroment and for your JS enviroment (you might already be loading an Ajax library).

like image 102
Fran Cano Avatar answered Oct 05 '22 15:10

Fran Cano