vue3动态路由
时间: 2023-06-21 12:15:39 浏览: 56
Vue 3 中动态路由的实现与 Vue 2 相似,只需做一些小的调整。
首先,在路由配置文件中,你需要用冒号(:)来表示动态参数。例如:
```js
const routes = [
{
path: '/user/:id',
component: User
}
]
```
在上面的例子中,`:id` 表示一个动态参数,它可以匹配任何非空字符串。
然后,在你的组件中,你可以通过 `$route.params` 对象来获取动态参数的值。例如:
```html
<template>
<div>
<h2>User {{ $route.params.id }}</h2>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.$route.params.id)
}
}
</script>
```
在上面的例子中,我们通过 `$route.params.id` 来获取动态参数的值并在模板中进行渲染。在 `mounted` 钩子函数中,我们也可以直接访问它的值。
需要注意的是,在 Vue 3 中,如果你使用了 `setup` 函数来定义组件,你需要使用 `useRoute` 函数来访问 `$route` 对象,例如:
```html
<template>
<div>
<h2>User {{ routeParams.id }}</h2>
</div>
</template>
<script>
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
const routeParams = route.params
return {
routeParams
}
}
}
</script>
```
在上面的例子中,我们通过 `useRoute` 函数获取 `$route` 对象,并将动态参数值赋值给 `routeParams` 变量。然后,我们将 `routeParams` 变量返回给模板使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)