我试图用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 },
  ]
})

当前回答

与RouterLink

/ /与RouterLink < router-link :to="{name:"router-name", prams:{paramName: paramValue}}" > 路线的文本 < / router-link > / /方法 方法(){ 美元。路由器。push({name:'route-name', params:{paramName: paramValue}}) }

与方法

methods(){
  this.$router.push({name:'route-name', params:{paramName, paramValue}})
}

其他回答

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

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

如果您试图保留一些参数,同时更改其他参数,请确保复制vue路由器查询的状态,而不是重用它。

这是有效的,因为你正在创建一个未引用的副本:

  const query = Object.assign({}, this.$route.query);
  query.page = page;
  query.limit = rowsPerPage;
  await this.$router.push({ query });

而下面会导致Vue Router认为你在重复使用相同的查询,并导致navigationduplication错误:

  const query = this.$route.query;
  query.page = page;
  query.limit = rowsPerPage;
  await this.$router.push({ query });

当然,您可以分解查询对象,如下所示,但是您需要了解页面的所有查询参数,否则您可能会在结果导航中丢失它们。

  const { page, limit, ...otherParams } = this.$route.query;
  await this.$router.push(Object.assign({
    page: page,
    limit: rowsPerPage
  }, otherParams));
);

注意,虽然上面的例子是针对push()的,但它也适用于replace()。

用vue-router 3.1.6测试。

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

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

这与使用Composition API是等价的

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

router.push({ path: 'register', query: { plan: 'private' }})
</script>

您还可以使用Vue devtools以确保它按预期工作(通过检查您所处的给定路由),如下所示:https://stackoverflow.com/a/74136917/8816585


更新

这将同时挂载/卸载组件。一些普通的JS解决方案仍然是实现这一目的的最佳方式。

对于添加多个查询参数,这对我来说是有效的(从这里https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5)。

上面的答案很接近……不过是客体。赋值它会改变这个。$route。当执行Object.assign时,确保第一个参数是{}

this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });