代码之家  ›  专栏  ›  技术社区  ›  gespinha

使用Vue Router时,路由参数不会在Vue组件内渲染

  •  1
  • gespinha  · 技术社区  · 11 月前

    我已经让Vue路由器运行了这些路由:

    const routes = [
      {
        path: '/',
        name: 'home',
        params: {
          label: 'Home page'
        },
        component: Home
      },
      {
        path: '/group1',
        name: 'group1',
        params: {
          label: 'Group One'
        },
        redirect: { name: 'subgroup1' },
        children: [
          {
            path: 'subgroup1',
            name: 'subgroup1',
            params: { label: 'Sub Group One' },
            component: SubGroup1,
          },
          {
            path: 'subgroup2',
            name: 'subgroup2',
            params: { label: 'Sub Group Two' },
            component: SubGroup2,
          }
        ]
      }
    ]
    

    我想渲染 label 组件中的参数,但它不起作用。以下是我的组件示例:

    <template>
      <div>
        {{ $route.params.label}}
      </div>
    </template>
    

    我做错了什么?我怎样才能让它工作?

    2 回复  |  直到 11 月前
        1
  •  1
  •   Estus Flask    11 月前

    meta 用于路由元数据,如标签(因此得名),而 params 用于传递给路线的路线参数。

    应该是:

    ...
    path: '/',
    meta: { label: 'Home page' },
    ...
    

    {{ $route.meta.label}}
    
        2
  •  -1
  •   Dosunmu Afeez    11 月前

    访问此类标签不能通过当前路由完成,而是通过访问整个路由器本身完成。

    这可以通过使用这个来实现

    <template>
      <div>
        // pass the index of whatever route you want to access to get the 
        label
        {{ $router.options.routes[0].params.label }}
      </div>
    </template>
    

    我希望这能有所帮助。