【问题标题】:VueJS - updating URL with dynamic dataVueJS - 使用动态数据更新 URL
【发布时间】:2018-09-13 02:38:58
【问题描述】:

我有一个单页 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 之后,我完全被正确的处理方式弄糊涂了。

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

【问题讨论】:

    标签: vuejs2 vue-router


    【解决方案1】:

    无论您使用什么来更改值都需要触发路由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})
    

    【讨论】:

      【解决方案2】:

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

      • 从您的 URL 获取值

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

      • 根据您的foobaroofrab 变量设置 URL

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-15
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 2018-10-18
        • 1970-01-01
        • 2012-03-27
        相关资源
        最近更新 更多