能否手动调用vue-router解析器?获取任意URL的路由匹配对象
Vue Router 解析任意路径获取匹配路由对象
你要的需求完全可以通过Vue Router官方公开的router.resolve()方法实现,不用去寻找未暴露的内部解析器。
Vue 3 + Vue Router 4 用法:
调用路由实例的resolve方法传入目标路径,返回对象里的route属性就是和useRoute()结构一致的匹配路由对象。import { useRouter } from 'vue-router'; const router = useRouter(); // 解析目标路径 const resolvedResult = router.resolve('/one/two/three'); // 获取匹配到的路由对象 const matchedRoute = resolvedResult.route; // 可获取所有需要的信息: console.log(matchedRoute.name); // "path-one" console.log(matchedRoute.params); // { user: 'two', page: 'three' } console.log(matchedRoute.meta); // 对应路由的meta配置Vue 2 + Vue Router 3 用法:
逻辑一致,通过this.$router调用即可:const resolvedResult = this.$router.resolve('/one/two/three'); const matchedRoute = resolvedResult.route; // 同样能拿到匹配路由的所有属性
router.resolve()返回的对象除了route,还包含href(生成的完整URL)和location(标准化后的路由位置对象),完全满足导航前评估链接、确认路由匹配规则的需求。
内容的提问来源于stack exchange,提问作者Paulie
相关产品推荐
相关产品推荐

