Search code examples
vue.jsvue-router4

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?


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)
            }
        );
    }