【问题标题】:VueJS | How to get access to Router Parameter in my ComponentVueJS |如何访问我的组件中的路由器参数
【发布时间】:2018-07-04 22:17:04
【问题描述】:

我试图在我的 Entry 组件中访问我的参数 :id。我用道具试过了,但它不起作用。任何想法?什么都找不到。

export default new Router({
    routes: [{
        path: '/entry/:id',
        name: 'Entry',
        component: Entry
    }]
})

谢谢

【问题讨论】:

标签: vue.js vuejs2 vue-router


【解决方案1】:

您应该简单地使用$route.params.idthis.$route.params.id

阅读更多:https://router.vuejs.org/guide/essentials/dynamic-matching.html

你应该考虑使用道具:https://router.vuejs.org/en/essentials/passing-props.html

【讨论】:

  • 或者,this.$route.params.id
【解决方案2】:

虽然烧酒的回答是正确的,但我倾向于使用文档中称为“使用道具解耦路由器”的方法。

这可以通过将 props: true 选项添加到您的路由并在您的组件中定义一个属性来完成。

因此,在您的路线中,您将拥有:

export default new Router({
     routes: [{
          path: '/entry/:id',
          name: 'Entry',
          component: Entry,
          props: true
     }]
})

然后在你的组件中添加一个道具:

Vue.component('Entry', {
       template: '<div>ID: {{ id}}</div>',
       props:['id']
})

这都可以在文档中找到: Passing Props to Route Components

【讨论】:

    【解决方案3】:

    你可以在组件中使用

    this.$route.params.id
    

    【讨论】:

    • 请考虑在您的回答中添加更多信息
    【解决方案4】:

    在 html 中 &lt;div&gt;{{$route.params.id}}&lt;/div&gt;

    在脚本中this.$route.params.id

    【讨论】:

      【解决方案5】:
      <template>
          <div>
            <p>{{id}}</p>
          </div>
      </template>
      
      <script>
          export default {
              data() {
                  return {
                      id:this.$route.params.id
                  }
              },
          }
      </script>
      

      【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2021-05-31
      • 2020-09-25
      • 2016-04-14
      • 2018-07-07
      • 2020-10-24
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      相关资源
      最近更新 更多