简体   繁体   中英

Vue router: Dynamically set query key inside router.push()

I am new to Vue and I have created a project where I perform GET-requests based on current URL.

I have a function where I want to be able to set the dynamic value of filterType to the query key inside the router.push().

The function I have now just pushes filterType as a string. Ive been researching and havent found any answers regarding this issue. Grateful for any input or wisdom.

setFilter(filterType, filterValue){
    if(filterValue){
        this.$router.push({ query: Object.assign({}, this.$route.query, { filterType: filterValue })}).catch(err =>{});
    }
    else {
        let query = Object.assign({}, this.$route.query);
        delete query.filterType;
        this.$router.replace({ query }).catch(err =>{});
    }
},

Assign it as a key to the query object:

if(filterValue){
  const query = this.$route.query
  query[filterType] = filterValue
  this.$router.push({path:'/', query:query})
}

Try this code

let newQuery = {filterType: filterValue};
this.$router.push({name: 'route-name', query: {...this.$route.query, ...newQuery}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM