Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - How do I just have one routing path to load the same component with different ID's

I have three files and they are router.js, App.vue and Contents.vue:

router.js:

{
  path: '/views/frames/viewContentId1',
  name: 'letsCheck1',
  component: () => import('./views/frames/Contents.vue'),
  props: {
    id: '1'
  }
},
{
  path: '/views/frames/viewContentId2',
  name: 'letsCheck2',
  component: () => import('./views/frames/Contents.vue'),
  props: {
    id: '2'
  }
},

App.vue:

<div class=" Button to display content of Id1">
  <vs-button @click="$router.push({name: 'letsCheck1'}).catch(err => {})">Explore Light</vs-button>
</div>

<div class=" Button to display content of Id2">
  <vs-button @click="$router.push({name: 'letsCheck2'}).catch(err => {})">Explore Deep</vs-button>
</div>

Contents.vue:

<div class="Whole contents are present here">
  <p> Here this content is same for both the id</p>
    <span v-if="id === '1' ">Top Notch1</span>
    <span v-if="id === '2' ">Top Notch2</span>
  <p> Here again this content is same for both the id</p>
</div>
<script>
props: {
  id: String,
  required: true
}
</script>

I am actually looking to make code effective in router.js. I have specified the id twice, but suppose I want to add more id's which have the same information to display with slight changes, as you can see in Contents.vue, I have shown the slight changes by using the v-if directive.

So I want to know how can I define the path only once and how to specify the id in the buttons, such that it loads the content by the respective id.

like image 993
Quantum Avatar asked Nov 20 '25 23:11

Quantum


1 Answers

You can do with dynamic-routing. Please check the documentation.

Router.js

{
  path: '/views/frames/:viewContentId',
  name: 'letsCheck1',
  component: () => import('./views/frames/Contents.vue'),
  props: {
    id: '1'
  }
},

App.vue

<div class=" Button to display content of Id1">
  <vs-button @click="$router.push({name: 'letsCheck1',params: { viewContentId: '1' }})">Explore Light</vs-button>
</div>

<div class=" Button to display content of Id2">
  <vs-button @click="$router.push({name: 'letsCheck1',params: { viewContentId: '2' }})">Explore Light</vs-button>
</div>

Contents.vue

<div class="Whole contents are present here">
    <p> Here this content is same for both the id</p>
        <span v-if="$route.params.viewContentId === '1' ">Top Notch1</span>
        <span v-if="$route.params.viewContentId === '2' ">Top Notch2</span>
    <p> Here again this content is same for both the id</p>
</div>
like image 55
Nilesh Patel Avatar answered Nov 22 '25 15:11

Nilesh Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!