要将路由参数作为 props 传递,您应该将路由上的 props 选项设置为 true。这会将 route.params 将会接收 props 属性参数,示例代码如下:
<!-- 堆代码 duidaima.com -->
const User = {
props: ['id'],
template: '<h1>Your Id is {{id}} </h1>'
}
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{
path: '/home',
component: { template: '<h1>Home</h1>' }
},
{
path: '/about',
component: { template: '<h1>About Us</h1>' }
},
{
path: '/user/:id',
name: 'user',
component: User,
props: true
}
]
});
const app = Vue.createApp({
methods: {
changeRoute(route) {
// `route` is either a string or object
router.push(route);
}
},
template: `
<div id="rendered-content">
<div>
<button @click="changeRoute('home')">Home</button>
<button @click="changeRoute('about')">About Us</button>
<button @click="changeRoute({path: '/user/123'})">Get ID</button>
</div>
<div>
<router-view></router-view>
</div>
</div>
`
});
app.use(router);
app.mount('#props')
您可以使用 Vue Router 将 props 设置为函数。这使您可以更精细地控制 Vue Router 传递给 Vue 组件的 props。
Vue Router 使用路由对象作为第一个参数调用你的 props 函数
{
path: '/user/:id',
name: 'user',
component: {
template: `
<div>
<h1>id is {{id}}</h1>
<h1>showProfilePicture is {{showProfilePicture}}</h1>
</div>
`
},
props: route => ({
id: route.params.id, // Pull `id` from route params
showProfilePicture: true // Hard code `showProfilePicture`
})
}