In Vue.js, dynamic routes are routes that can match a variety of patterns, rather than a static path. You can create dynamic routes by using route parameters. Here's a basic example of how you can create dynamic routes in Vue.js:
Let's say you have a resource like posts, and you want to create a dynamic route to display a specific post based on its ID. Here's how you can achieve that:
Set up your Vue Router:
In your router/index.js
file, define a dynamic route with a parameter (e.g., postId
):
javascriptimport Vue from 'vue'
import Router from 'vue-router'
import Post from '@/views/Post.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/post/:postId',
name: 'post',
component: Post,
props: true // This allows you to pass route params as props to your component
},
// Other routes...
]
})
Create your component:
Create a component (e.g., views/Post.vue
) that will be responsible for displaying the post:
html<template>
<div>
<h2>Post {{ postId }}</h2>
<!-- Your post content goes here -->
</div>
</template>
<script>
export default {
props: ['postId'],
mounted() {
// Fetch and display the post content based on this.postId
// You can use Vuex or an API service to fetch the data
}
}
</script>
<style scoped>
/* Your component styles go here */
</style>
In this example, :postId
in the route path creates a dynamic parameter. This parameter will be available in your component as a prop named postId
. You can then use this prop to fetch and display the corresponding post content.
Navigate to dynamic routes:
In your application, when you want to navigate to a specific post, use the following code:
html<router-link :to="{ name: 'post', params: { postId: 1 }}">Post 1</router-link>
Replace 1
with the actual ID of the post you want to display.
By following these steps, you can create dynamic routes in Vue.js and pass parameters to your components based on the route. Adjust the example to fit your specific use case and resource links.