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.
Related
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.
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.
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.
Using #angular/router": "3.4.7".
Proposed solution here doesn't work anymore.
/**
The ProductComponent depending on the url displays one of two info
components rendered in a named outlet called 'productOutlet'.
*/
#Component({
selector: 'product',
template:
` <router-outlet></router-outlet>
<router-outlet name="productOutlet"></router-outlet>
`
})
export class ProductComponent{
}
#NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{
path: 'product',
component: ProductComponent,
children: [
{
path: '',
component: ProductOverviewComponent,
outlet: 'productOutlet'},
{
path: 'details',
component: ProductDetailsComponent,
outlet: 'productOutlet' }
]
}
]
)],
declarations: [
ProductComponent,
ProductHeaderComponent,
ProductOverviewComponent,
ProductDetailsComponent
exports: [
ProductComponent,
ProductHeaderComponent,
ProductOverviewComponent,
ProductDetailsComponent
]
})
export class ProductModule {
}
Manual navigation works as expected
http://localhost:5000/app/build/#/product-module/product (correctly displays overview component in named outlet)
http://localhost:5000/app/build/#/product-module/product/(productOutlet:details)
(correctly displays details component in named outlet)
THE PROBLEM
Cannot figure out the correct way to perform programatical navigation:
this.router.navigateByUrl('/(productOutlet:details)');
this.router.navigate(['', { outlets: { productOutlet: 'details' } }]);
Following errors occur:
Error: Cannot match any routes. URL Segment: 'details'.
You can navigate programatically like this
this.router.navigate([{ outlets: { outletName: ['navigatingPath'] } }], { skipLocationChange: true });
Note: skipLocationChange is use to hide the url from the address bar.
Refer the official document : https://angular.io/guide/router
You can try relative navigation as
this.router.navigate(['new'],{relativeTo:this.route})
For this you will have to inject current router snapshot and Activated route in component as
import { Router,ActivatedRoute } from "#angular/router";
constructor(private router:Router,private route:ActivatedRoute ){}
I have just upgraded from router-deprecated to "#angular/router": "3.0.0-alpha.8". I have everything working inside the application but it's not working when I navigate to a URL.
For example, I use this routerLink:
<a [routerLink]="['/app/dashboard']">DashBoard</a>
which produces this URL:
http://localhost:54675/app/dashboard
And that view loads with no problem.
However, if I just enter that URL in the browser and press return I get a blank white page. Nothing in the console and the source is empty.
I am using the default HTML5 locationStrategy - not the hash (#).
This worked with router-deprecated.
I can't figure out what I could be doing wrong since everything else is working.
When I navigate to a fill URL I notice that I get a 404 error in the console. That's because nothing on the server matches this URL, but it needs to load the app then route to that URL.
Here are my route files:
app.routes.ts:
export const routes: RouterConfig = ([
{ path: '', component: SplashComponent },
{ path: 'login', component: SplashComponent },
...MainRoutes
]);
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
main.routes.ts
export const MainRoutes: RouterConfig = [
{
path: 'app',
component: MainLayoutComponent,
children: [
{ path: 'dashboard', component: DashboardComponent},
{ path: '', component: DashboardComponent },
{ path: 'user', component: AccountEditComponent },
{ path: 'admin', component: ManageComponent }
]
}
];
My Angular2 app was hosted in an DotNet Core application. I had to configure it to redirect to index.html on URLs that returned 404s. I followed this article:
http://asp.net-hacker.rocks/2016/04/04/aspnetcore-and-angular2-part1.html