How to set URL query params in Vue with Vue-Router

前端 未结 9 811
梦如初夏
梦如初夏 2020-12-23 20:24

I am trying to set query params with Vue-router when changing input fields, I don\'t want to navigate to some other page but just want to modify url query params on the same

9条回答
  •  悲哀的现实
    2020-12-23 20:50

    To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

        setQuery(query){
            let obj = Object.assign({}, this.$route.query);
    
            Object.keys(query).forEach(key => {
                let value = query[key];
                if(value){
                    obj[key] = value
                } else {
                    delete obj[key]
                }
            })
            this.$router.replace({
                ...this.$router.currentRoute,
                query: obj
            })
        },
    
        removeQuery(queryNameArray){
            let obj = {}
            queryNameArray.forEach(key => {
                obj[key] = null
            })
            this.setQuery(obj)
        },
    

提交回复
热议问题