vue routing: list-detail view on the same page with correct routing/urls

Viewed 530

I'm trying to show a list of items and an item detail on the same page. When one clicks on an item in the list, that item is shown in the detail view and the url should change to /items/item_id

This is how I do it now, but of course the url doesn't change:

<div>
    <items-table :items="items" @OnItemClicked="selectedItem=$event"></items-table>
</div>

<div v-if="selectedItem">
    <item-detail :item="selectedItem"></contact-card>
</div>

I tried changing the url by doing router.push(...) when one clicks on an item in the list, but this reloads the whole page. I've also looked for a nested router-view, but I'm not sure if that is the correct way or how to implement that.

What is the best way in vue.js to show a list of items and an item detail on the same page?

1 Answers

You could setup a nested route on that page for the detail view:

  1. In your router config, add a children array to the list-view route. The child route config should have a dynamic path parameter (prefixed with a :) to contain the item ID, which will appear in the URL when the route is shown:

    // router.js
    export default new VueRouter({
      routes: [
        {
          path: '/items',
          component: () => import('@/views/ListView.vue'),
          children: [
            {
              path: ':itemId',
              props: true,
              component: () => import('@/views/ListDetailView.vue')
            }
          ]
        }
      ]
    })
    
  2. In the list-view component, add a router-view. This is separate from the main router-view in the root view (e.g., App.vue).

    <div class="list-view">
      <items-table :items="items"></items-table>
      <router-view></router-view>
    </div>
    
  3. In the items-table component, add a router-link for each item, with a to path that matches the URL of the detail view from step 1 (i.e., /items/ + the item ID):

    <router-link :to="`/items/${item.id}`">{{ item.name }}</router-link>
    

demo

Related