vue3动态路由的实现
时间: 2023-11-06 08:48:11 浏览: 148
Vue 3中动态路由的实现与Vue 2有一些不同。在Vue 3中,可以使用`createRouter`函数来创建路由实例,并通过`routes`选项来定义路由配置。要实现动态路由,可以使用`route`方法来添加动态路径参数。
下面是一个基本的Vue 3动态路由的实现示例:
```javascript
// main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './views/Home.vue'
import Post from './views/Post.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/post/:id', component: Post }
]
const router = createRouter({
history: createWebHistory(),
routes
})
const app = createApp(App)
app.use(router)
app.mount('#app')
```
在上面的示例中,我们创建了两个路由:一个是根路径'/'对应Home组件,另一个是动态路径'/post/:id'对应Post组件。其中':id'是参数占位符,可以动态传入不同的值。
在Post组件中,可以通过`$route.params`来获取参数值。例如,要获取动态路径中的id参数值,可以使用`$route.params.id`。
```javascript
// Post.vue
<template>
<div>
<h2>Post Page</h2>
<p>Post ID: {{ $route.params.id }}</p>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.$route.params.id)
}
}
</script>
```
以上就是Vue 3中动态路由的基本实现方法。通过使用路由配置中的动态路径参数,可以实现根据不同参数值加载不同的组件或页面内容。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)