vue3组合式API如何实现路由传参
时间: 2023-07-07 12:24:59 浏览: 313
在Vue3中,可以使用组合式API实现路由传参。具体实现步骤如下:
1. 在路由配置中,设置`props`属性为`true`或者一个函数。例如:
```javascript
const routes = [
{
path: '/example/:id',
name: 'example',
component: Example,
props: true
},
// 或者
{
path: '/example/:id',
name: 'example',
component: Example,
props: route => ({ id: route.params.id })
}
]
```
2. 在组件中,使用`props`函数获取路由传参。例如:
```javascript
import { defineComponent, ref } from 'vue'
export default defineComponent({
props: {
id: {
type: String,
required: true
}
},
setup(props) {
// 使用props.id获取路由传参
const id = ref(props.id)
// ...
return { id }
}
})
```
注意:如果使用了`props: true`,则组件中的`props`属性名称必须与路由参数名称相同。如果使用了函数,则可以根据需要自定义`props`属性名称。
3. 在模板中,直接使用`props`属性即可获取路由传参。例如:
```html
<template>
<div>{{ id }}</div>
</template>
```
注意:`props`属性是一个响应式对象,当路由参数变化时,模板会自动更新。
阅读全文
相关推荐
















