Home > Software engineering >  Vue Router Push How To Set Optional Query Parameters?
Vue Router Push How To Set Optional Query Parameters?

Time:06-03

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?

CodePudding user response:

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

CodePudding user response:

Try to define the an array of filters as strings then iterate over them and assign only the property which has a valid value:


let filters=['checkedTags', 'checkedSales', 'checkedRatings', 'checkedDateAdded', 'sortBy', 'minPrice', 'maxPrice']

let queryParams=filters.reduce((acc,curr)=>{
   if (this[curr]!==[] || this[curr]!==''){
      acc[curr]=this[curr]
   }
  return acc
 },{})

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

  • Related