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

前端 未结 9 745
梦如初夏
梦如初夏 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:49

    Without reloading the page or refreshing the dom, history.pushState can do the job.
    Add this method in your component or elsewhere to do that:

    addParamsToLocation(params) {
      history.pushState(
        {},
        null,
        this.$route.path +
          '?' +
          Object.keys(params)
            .map(key => {
              return (
                encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
              )
            })
            .join('&')
      )
    }
    

    So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

    To add query params to current location without pushing a new history entry, use history.replaceState instead.

    Tested with Vue 2.6.10 and Nuxt 2.8.1.

    Be careful with this method!
    Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

    0 讨论(0)
  • 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)
        },
    
    0 讨论(0)
  • 2020-12-23 20:54

    I normally use the history object for this. It also does not reload the page.

    Example:

    history.pushState({}, '', 
                    `/pagepath/path?query=${this.myQueryParam}`);
    
    0 讨论(0)
提交回复
热议问题