Get the parent name of children's route Vue js - vuejs3

I have this route that has a children. I can retrieve the name of the route however it is only applicable to the name of the children.
const routes = [
{
path: '/',
name: 'Home', // <--- I want to get this route name
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('src/pages/Home/Index.vue') },
{ path: '/patient', component: () => import('src/pages/Home/Patient.vue') },
]
},
{
path: '/auth',
name: 'Auth', <--- I want to get this route name
component: () => import('layouts/AuthLayout.vue'),
children: [
{ path: '', component: () => import('pages/Login.vue') },
//{ path: '', component: () => import('pages/Login.vue') }
]
},
// Always leave this as last one,
// but you can also remove it
{
path: '/:catchAll(.*)*',
component: () => import('pages/Error404.vue')
}
]
export default routes
Then I tried remove all named routes from the children and assigned a name to the parent but it gives me
undefined whenever I console.log($route.name) on the MainLayout.vue

I'm not sure if this is really the right way of getting the parent's route name but I have achieved it using route.matched
import { useRoute } from 'vue-router'
...
const path = computed(() => $route.matched[0].name ) //[0] first one
This should return the component name Home

I think you're looking for the immediate parent of the current active route .. yes?
In that case, you do as previously mentioned use this.$route.matched, but not as stated. The current route is the last item in $route.matched array, so to get the immediate parent you can use:
const parent = this.$route.matched[this.$route.matched.length - 2]
const { name, params, query } = parent
this.$router.push({ name, params, query })

In my vue.js 3 project I am using vite-plugin-pages and for some reason #Shulz's solution gives me route.matched[0].name: undefined. So, doing things as mentioned below helped:
In <template>
<router-link to='/the-page' :class='{ "active": subIsActive("/the-page") }'> The Page </router-link>
In <script>
const subIsActive = (input) => {
const paths = Array.isArray(input) ? input : [input];
return paths.some((path) => route.path.indexOf(path) === 0);
};
but, as I am using vite-plugin-pages I found another solution and I followed this approach to fix my issue.

Related

clear URL when route changes

I've got Vue app with this router file in it:
const routes = [
{
path: '/',
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('pages/IndexPage.vue') },
{ path: '/contacts', component: () => import('pages/ContactsPage.vue') },
{ path: '/settings', component: () => import('pages/GeneralSettings.vue') },
]
},
{
path: '/:catchAll(.*)*',
component: () => import('pages/ErrorNotFound.vue')
}
]
export default routes
Inside the IndexPage I've created this method to show the id in the URL , so I can use it later:
const setURL = (item: Store) => {
const searchURL = new URL(window.location.toString());
searchURL.searchParams.set('itemid', item.id);
window.history.pushState({}, '', searchURL);
}
This method works just fine, but when I try to open eg.: the Contact page the URL looks like this:
http://localhost:8080/?itemid=1#/contacts
This is not working, because the URL should be the following:
http://localhost:8080/#/contacts
Is there any way to remove the itemid when clicking a link?
I'm using Quasar and composition api.
I think the main problem is in the setUrl function.
When using vue-router, I suggest you try not to interfere with the url manually as much as possible.
If you want to add a query to the url without refreshing the page, you can use the router.replace() method.
import { useRouter } from "vue-router"
const router = useRouter()
const setURL = (item: Store) => {
router.replace({ query: { itemId: item.id } })
}
Your routes should work fine when you edit them this way.

Vue Router having both query and path properties

I have the need for a route which takes properties from both the path as well as the query, but I can not get it working:
{
path: 'clients',
component: () => import('pages/client/Index.vue'),
props: route => ({ filter: route.query.filter }),
children: [
{
path: ':clientId',
props: route => ({ filter: route.query.filter, clientId: route.path.clientId }),
component: () => import('pages/client/Index.vue')
}
]
}
I can get it to work, with either the query or the path props, but making both work seems to be impossible.
I also tried props: true which, if I understood the documentation should simply work, but it does not. In my Component (Index.vue). Itried definning the props in the following two ways:
props: {
clientId: {
type: String,
default: ''
},
filter: {
type: String,
default: ''
}
},
props: {
...RouterLink.props
},
Neither of them make a difference, it mainly depends on how I define the routes in router.js.
What am I doing wrong and how can I get both path and query props working at the same time on the same route?
Tia
Here is your error:
props: route => ({ filter: route.query.filter, clientId: route.path.clientId })
You should use params instead of path
props: route => ({ filter: route.query.filter, clientId: route.params.clientId })
Here is the solution:
https://stackblitz.com/edit/vue-azs4wh?file=src/router.js
Docs: Dynamic Route Matching with Params

How can i pass an object through props to a View Component

I want to send an object through props from Main component, to another component (Character.vue).
Character.vue isn't called like a child:
Main.vue has an object called character
<Character :prop="character" />
Character.vue it's a View Component. I want to do some like
Main.vue has a button with an click action:
#click="sendProp"
And the function:
const sendProp = () => {
router.push({
name: "Character",
params: {
character: { ...props.character },
},
});
}
In router I have:
{
path: '/character',
name: 'Character',
props: true,
component: () => import(/* webpackChunkName: "character" */ '../views/Character.vue')
}
I want to execute sendProp function, go to /character route, and get an object in their props.
But when localhost/character is opened by sendProp function, i don't receive the character prop.
Someone can help me? Thanks

How to make index.js Vue router dynamic?

I'm trying to make index.js in vue.js dynamic instead of me having to go in a manually add a page path or name.
What i'm hoping for is to use $route from the data (see screenshot ) in router > index.js so something like the below if possible.
{
path: $route.path,
name: $route.name,
component: () =>
import(/* webpackChunkName: "about" */ "../views/mainPages.vue"),
props: true,
},
instead of having to manually add a new block every time. See example
{
path: "/jobs/other-jobs",
name: "other-jobs",
component: () =>
import(/* webpackChunkName: "about" */ "../views/mainPages.vue"),
props: true,
},
Any help would be greatly appreciated.

want to navigate from one page to another page using child module

Child Module
​const routes: Routes = [
{ path: '', component: ProcComponent,
children:[{
path: '/LoadProcResultsdata/:procResults', component: ProcResultsComponent,
}]
}
];
App.Module.ts
​const routes: Routes = [
{ path: 'app', component: AppComponent },
{ path: 'home', component: HomeComponent },
{ path: 'treeview', component: TreeViewComponent },
{path:'Proc', loadChildren:'app/proc/Proc.Module#ProcModule'}
];
My code
this.router.navigate(['/LoadProcResultsdata/'],{ queryParams: { procResults:this.results } });
But I am getting following error.
core.umd.js:3064 EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'LoadProcResultsdata'
Error: Cannot match any routes. URL Segment: 'LoadProcResultsdata'
There are couple of issues,
remove front / from the path,
children:[{
path: '/LoadProcResultsdata/:procResults', component: ProcResultsComponent,
}]
Also you need to use route params rather query params, so you can use below,
this.router.navigate(['/LoadProcResultsdata', this.results]);
I am assuming this.results is some ID, so the resulting url becomes
/LoadProcResultsdata/<id>
Read more abour route parmeters here.
Update:
you can do that but not with route params, just with queryParams, remove :procResults, and use similar code like below,
let extra: any = ['abc','xyz'];
let navigationExtras: NavigationExtras = {
queryParams:extra
};
this.router.navigate(['/LoadProcResultsdata'],navigationExtras);
and in the navigted component subscribe to ActivatedRoute queryParams,
constructor( private route: ActivatedRoute) {
route.queryParams.subscribe(params => {
console.log(params);
})
}
Check this Plunker!!
another Plunker with Lazy loaded module.

Resources