我有一个 Vue Router 路由设置,如下所示:
[
{
path: '/regions',
name: 'regions',
component: () => import(/* webpackChunkName: "regions" */ '../views/RegionsView.vue'),
props: {
endpoint: '/admin/regions/index'
},
meta: {
auth: true,
role: ['admin'],
permission: 'region-view'
}
}
]
我正在尝试从
props
函数中的路线访问 beforeEach()
,我该怎么做?
router.beforeEach((
to: RouteLocationNormalized,
from: RouteLocationNormalized,
next: NavigationGuardNext
) => {
// console.log(to.props)???
next()
})
您可以使用
meta
键在路线中传递数据。
// route definition
[
{
path: '/regions',
name: 'regions',
component: () => import(/* webpackChunkName: "regions" */ '../views/RegionsView.vue'),
// props: {
// endpoint: '/admin/regions/index',
// },
meta: {
auth: true,
role: ['admin'],
permission: 'region-view',
props: {
endpoint: '/admin/regions/index',
},
},
},
];
然后就可以在
beforeEach
和其他守卫中访问了:
// hook
Router.beforeEach((from, to, next) => {
console.log('from', from.meta.props?.endpoint);
console.log('to', to.meta.props?.endpoint);
next();
});
根据当前路由器页面,道具数据将位于
from
或 to
或无。
或者,在使用 Route hook 的组件中:
// ../views/RegionsView.vue
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
console.log('props', route.meta.props?.endpoint);
</script>