如何判断子组件的父组件来源并实现动态返回路由?
解决方案
当然可以实现,给你几种靠谱的思路:
1. 通过当前路由路径直接判断
如果子组件所在的路由路径里包含parent1或parent2的标识,直接通过路径字符串判断:
<template> <button open ref="backBtn" :back="getBackPath()" /> </template> <script> export default { methods: { getBackPath() { const id = this.$route.params.id; // 检查当前路由路径是否包含parent1 return this.$route.path.includes('/parent1/') ? `/parent1/${id}/home` : `/parent2/${id}/home`; } } } </script>
2. 通过路由匹配层级判断(更规范)
如果你的路由配置里,parent1和parent2是明确的父路由节点(有对应的路由name),可以通过$route.matched来匹配父路由:
<template> <button open ref="backBtn" :back="getBackPath()" /> </template> <script> export default { methods: { getBackPath() { const id = this.$route.params.id; // 从路由匹配列表里找到父路由节点 const parentRoute = this.$route.matched.find(route => route.name === 'parent1' || route.name === 'parent2' ); return parentRoute?.name === 'parent1' ? `/parent1/${id}/home` : `/parent2/${id}/home`; } } } </script>
3. 父组件传递标识(最可靠)
直接在父组件使用子组件时,传递一个标识告诉子组件当前的父类型,这种方式不受路由变化影响,最稳定:
子组件代码:
<template> <button open ref="backBtn" :back="`/${parentType}/${$route.params.id}/home`" /> </template> <script> export default { props: { parentType: { type: String, required: true, // 限制只能传指定值 validator: val => ['parent1', 'parent2'].includes(val) } } } </script>
在parent1组件里使用子组件:
<ChildComponent parentType="parent1" />
在parent2组件里使用子组件:
<ChildComponent parentType="parent2" />
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

