我试图用Vue-router在改变输入字段时设置查询参数,我不想导航到其他页面,但只想修改url查询参数在同一页面上,我这样做:

this.$router.replace({ query: { q1: "q1" } })

但这也会刷新页面并将y位置设置为0,即滚动到页面顶部。这是设置URL查询参数的正确方法还是有更好的方法。


编辑:

这是我的路由器代码:

export default new Router({
  mode: 'history',
  scrollBehavior: (to, from, savedPosition)  => {
    if (to.hash) {
      return {selector: to.hash}
    } else {
      return {x: 0, y: 0}
    }
  },
  routes: [
    ....... 
    { path: '/user/:id', component: UserView },
  ]
})

当前回答

无需重新加载页面或刷新dom,历史记录。pushState可以做这个工作。 在你的组件或其他地方添加这个方法:

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

因此,在组件的任何地方,调用addParamsToLocation({foo: 'bar'})在窗口中推当前位置的查询参数。历史堆栈。

要将查询参数添加到当前位置,而不推入新的历史记录项,请使用history。replaceState代替。

用Vue 2.6.10和Nuxt 2.8.1测试。

使用这种方法要小心! Vue路由器不知道url已经改变,所以它不会在推送状态后反映url。

其他回答

下面是我在不刷新页面的情况下更新URL中的查询参数的简单解决方案。确保它适用于您的用例。

const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });

无需重新加载页面或刷新dom,历史记录。pushState可以做这个工作。 在你的组件或其他地方添加这个方法:

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

因此,在组件的任何地方,调用addParamsToLocation({foo: 'bar'})在窗口中推当前位置的查询参数。历史堆栈。

要将查询参数添加到当前位置,而不推入新的历史记录项,请使用history。replaceState代替。

用Vue 2.6.10和Nuxt 2.8.1测试。

使用这种方法要小心! Vue路由器不知道url已经改变,所以它不会在推送状态后反映url。

实际上你可以这样推query: this.$router。推送({query: {plan: 'private'}})

基于:https://github.com/vuejs/vue-router/issues/1631

this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })

vue路由器在更新时不断重新加载页面,最好的解决方案是

  const url = new URL(window.location);
  url.searchParams.set('q', 'q');
  window.history.pushState({}, '', url);