VueJS - 使用动态数据更新 URL

VueJS - updating URL with dynamic data

我有一个单页 VueJS 应用程序,其中包含一些我想编码到 URL.

中的数据变量

举个例子,如果我的路由配置是(我不确定语法是否正确):

routes: [
    {
        path: '/:foo/:bar/:oof/:rab',
        component: App
    }

组件是:

<script>
export default {
  name: "App",
  data: function() {
    return {
      foo: 1,
      bar: 2,
      oof: 3,
      rab: 4
    }
  }
}

那么 URL 就是 http://www.example.com/#/1/2/3/4

如果 foo 更改为 9999,URL 将自动更新:http://www.example.com/#/9999/2/3/4

它还会通过将 URL 值加载到数据中来响应用户更改 URL 或使用不同的 URL 打开应用程序。

我认为这会相对简单,但经过 Google 我对正确的处理方式感到非常困惑。

非常感谢任何帮助/示例/解决方案。

无论您使用什么来更改值,都需要触发路由 push。例如

methods: {
  changeFoo (newFoo) {
    // you can set foo but it probably won't matter because you're navigating away
    this.foo = newFoo
    this.$router.push(`/${newFoo}/${this.bar}/${this.oof}/${this.rab}`)
  }

https://router.vuejs.org/guide/essentials/navigation.html


如果你 name your route 可能会更容易,例如

routes: [{
  name: 'home',
  path: '/:foo/:bar/:oof/:rab',
  component: App
}]

然后你可以使用像

这样的东西
this.$router.push({name: 'home', params: this.$data})

您似乎想要实现两件事,但我不确定您的示例中哪个在您的理想操作顺序中排在第一位:

  • 从您的 URL

    获取值

    这可以通过 this.$route.params 实现,它将是一个包含您要查找的值的对象。

  • 根据您的 foobaroofrab 变量设置 URL

    您可以使用 this.$router.push() 来执行此操作:vue-router docs