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

当前回答

这与使用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解决方案仍然是实现这一目的的最佳方式。

其他回答

好吧,所以我一直试图添加一个参数到我现有的url wich已经有一个星期的params现在lol, 原始网址:http://localhost:3000/somelink?param1=test1 我一直在尝试:

this.$router.push({path: this.$route.path, query: {param2: test2} });

这段代码只是删除param1并变成 http://localhost:3000/somelink?param2=test2

为了解决这个问题,我使用了fullPath

this.$router.push({path: this.$route.fullPath, query: {param2: test2} });

现在我成功地在旧的参数和结果添加参数

http://localhost:3000/somelink?param1=test1&param2=test2

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

这与使用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解决方案仍然是实现这一目的的最佳方式。

我的解决方案,没有刷新页面,没有错误避免多余的导航到当前位置

    this.$router.replace(
      {
        query: Object.assign({ ...this.$route.query }, { newParam: 'value' }),
      },
      () => {}
    )

与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}})
}