3

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 :)

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure what we are importing, with import qs ?
You want { encodeValuesOnly: true }, not encode: false
2

Addition to Martin's comment,

Exact Router config should be :

// https://github.com/ljharb/qs
import qs from 'qs';

const router = new Router({
    routes: [
        // ...
    ],
    // set custom query resolver
    parseQuery(query) {
        return qs.parse(query);
    },
    stringifyQuery(query) {
        var result = qs.stringify(query);

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

and query parameters inside routes will be automatically converted url string and parsed as an object when accessing $router.query .

3 Comments

the encode false is missing in your example: qs.stringify(query, {encode: false});
I suspect youd actually want { encodeValuesOnly: true }, not encode: false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.