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

前端 未结 9 797
梦如初夏
梦如初夏 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.

提交回复
热议问题