Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue Router Push How To Set Optional Query Parameters?

I am building a site with a filter and sort menu. When the user clicks on one of the filters, I want that filter option added to the url and then the page to update using this.$router.push. This works fine when I add all of the filters at the same time, but my url shows all of the filters, even if they haven’t been selected yet? I changed my code to only show optional queries, but now it doesn’t work:

processCheckedTags() {
            
    let queryParams = "";

    Object.assign(queryParams, 
        this.checkedTags !== [] ? {checkedTags: this.checkedTags} : null,
        this.checkedSales !== [] ? {checkedSales: this.checkedSales} : null,
        this.checkedRatings !== "" ? {checkedRatings: this.checkedRatings} : null,
        this.checkedDateAdded !== "" ? {checkedDateAdded: this.checkedDateAdded} : null,
        this.sortBy !== "" ? {sortBy: this.sortBy} : null,
        this.minPrice !== "" ? {minPrice: this.minPrice} : null,
        this.maxPrice !== "" ? {maxPrice: this.maxPrice} : null,
    );

    this.$router.push(
        { 
            path: this.$route.params.mainNavigation, 
            query: queryParams
        }
    );
}

How do I add optional queries to this.$router.push?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With the help of lodash pickBy, you could rewrite what you need in a very succinct way:

processCheckedTags() {
    const params = {
        checkedTags: this.checkedTags,
        checkedSales: this.checkedSales,
        checkedRatings: this.checkedRatings,
        checkedDateAdded: this.checkedDateAdded,
        sortBy: this.sortBy,
        minPrice: this.minPrice,
        maxPrice: this.maxPrice,
    };

    this.$router.push(
        {
            path: this.$route.params.mainNavigation,
            query: _.pickBy(params)
        }
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading