Vue Router,构造路由

Vue Router, construct a route

我正在我的应用程序中制作一个带有搜索字段的数据 table,我想实现以下行为:

When a user types a research, the URL gets updated. If a user clicks on a link and hit "back" from his navigator, he gets back to his last search.

目前,我正在做以下事情:

export default {
  data () {
    return {
      search: ''
    }
  },
  watch: {
    search (value) {
      this.$router.replace('/products?search=' + value)
    }
  }
}

如您所见,我正在使用路由器的replace功能。这让我可以让它发挥作用。而且它比 push 方法更好,因为如果用户在搜索期间点击 "back",他将转到他的最后一页而不是最后的研究,这正是我想要的。

但是,我不喜欢我写 URL 的方式。

我很想做这样的东西:

watch: {
  search (value) {
    let route = new Route(this.$route)

    route.query.search = value

    this.$router.replace(route.getPath())
  }
}

因为,假设用户有其他参数,例如分页之类的,它们将被删除。我想要一个采用我的实际 url 和 add/replace 查询字符串参数的方法。

这是我可以使用 Vue Router 实现的东西还是我需要做其他事情:其他包/Vanilla JS?

为什么不直接使用对象位置参数 $router.replace?例如:

watch: {
  search (value) {
    this.$router.replace({ path: 'products', query: { search: value }})
  }
}