Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue-router query parameter as array with keys

I need to generate a vue-router link that contains an array with string keys as a query parameter. I want the resulting URL to look like

url?param[key]=value

I need these kinds of query parameters to match an existing backend infrastructure, so renaming/refactoring them is not an option.

I've tried to use a router-link like the one below, but the param object just get's serialized as %5Bobject%20Object%5D. Maybe there is an option to change the way this object is serialized within vue-router?

<router-link :to="{name: 'xyz', query: {param: 'value'}}">link</router-link>

Does anyone have helpful input? Thank you :)

like image 696
Martin Avatar asked Mar 03 '26 06:03

Martin


1 Answers

After spending some time vue-router GitHub issues and their docs, I figured it out.

When creating your RouteConfig, import qs and set the parseQuery and stringifyQuery methods as follows:

parseQuery: (query: any): object => {
    return qs.parse(query);
},
stringifyQuery(query: any): string {
    let result = qs.stringify(query, {encode: false});

    return result ? ('?' + result) : '';
}

It is important to include {encode: false}, otherwise the square brackets will get URL encoded.

like image 196
Martin Avatar answered Mar 05 '26 00:03

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!