I have an understanding problem with the vue3 router.
how can i catch a wrong route with a function? After that I would like to influence the route depending on a database query. Here is my catchAll route as an example.
in the CheckfalseUrl function, however, the path is already on home! How can I intercept this beforehand.
var routes = [
{
paths: "/",
name: "home",
component: HomeView
},
{
path: "/contentPage",
name: "contentpage",
component: ContentView
}
{
path: "/:catchAll(.*)",
name: "home",
component: HomeView,
beforeEnter: checkfalseUrl
}
];
Related
I'm working on a Vue.js webapp. Recently I realized then when I want to change route (going home) from a Vuex action, it takes a lot of time and never end. It take 4600 MB RAM and 70% CPU.
Here is the indicted code:
impostaSelezionabili: ({ commit,dispatch }, payload) => {
commit("associazioniSelezionabiliImpostate", payload)
const prefe = payload.prefe
if (payload.associazioni.length == 1) {
commit("associazioneScelta", payload.associazioni[0].codAssociazione)
dispatch("toolbarManager/setToolbarVisibility", true, {root: true})
router.push({ path: '/' })
}
},
Everything works perfectly without router line, when I add router.push({ path: '/' }) it gets the problem.
Is there a way to solve?
Router config / Routes:
export const router = new Router({
mode: 'history',
routes: [
{ path: '/', component: HomePage, name: "Home", meta: "Home" },
{ path: '/servizi', component: ServiziPage, meta: "Servizi" },
{ path: '/servizi/:id', component: ServizioPage, meta: "Servizi" },
{ path: '/login', component: LoginForm},
{ path: '/corsi', component: Corsi, meta: "Corsi" },
{ path: '/corsidisponibili', component: Corsi, meta: "Corsi disponibili" },
// otherwise redirect to home
{ path: '*', redirect: '/', meta: "Home" }
]
});
Make sure that your router exists and that is not an import of vue-router. You need to use the router that you constructed with the new Router().
But I think that is the best way to solve it - that navigating inside a component after a Promise returned by that action will be resolved because in the current case your action isn`t pure.
Let's say I had this routes config:
pages
- index.vue
- admin
- login.vue
- register.vue
Is there a way to make /admin/login act as the index of admin routes? I want to simply redirect whoever hits /admin to /admin/login.
You could use middleware in /admin/index.vue, which has a redirect method in its context argument:
<script>
export default {
middleware({ redirect }) {
redirect(301, '/admin/login')
}
}
</script>
The vue-router supports redirect in the route definitions:
https://router.vuejs.org/guide/essentials/redirect-and-alias.html#redirect
const routes = [
/* ... */
{ path: '/admin', redirect: '/admin/login' },
{ path: '/admin/login', name: 'Login', component: LoginComponent },
{ path: '/admin/register', name: 'Register', component: RegisterComponent },
]
You can also define nested routes like so:
const routes = [
/* ... */
{
path: '/admin',
redirect: '/admin/login',
children: [
{
path: 'login',
name: 'Login',
component: LoginComponent
},
{
path: 'register',
name: 'Register',
component: RegisterComponent
}
]
}
]
How to use a guard to move to next rule of route instead of redirect to specific route?
for example, I have some routes:
routes: [
{ path: '/', component: Main },
{ path: '/about', component: About },
{ path: '/:product', component: Product },
{ path: '*', component: NotFoundException }
]
and in Product component I have beforeRouteEnter function like that:
beforeRouteEnter(to, from, next) {
const question = checkIfExist(to.params.product);
if (question) { next(); return;}
next();
}
if the product not exist then it should be redirect to NotFoundException component. in the stackoverflow example I see only example with redirect to specific url (like login) which is not helpful.
When I given url: '/some' then vue check if:
is / ? no => next route.
is /about ? no => next route.
is /:product ? no => next route.
display NotFoundException component.
You can reference the next route by route name.
First, name your exception route
routes: [
{ path: '/', component: Main },
{ path: '/about', component: About },
{ path: '/:product', component: Product },
{ path: '*', name: 'notFound', component: NotFoundException }
]
Then, create a variable which stores your beforeEnter Logic
const productExists = (to, from, next) => {
const question = checkIfExist(to.params.product);
if (question) { next(); return;}
next({
name: "notFound"
});
}
Add the route guard to the routes that you want to guard
routes: [
{ path: '/', component: Main },
{ path: '/about', component: About },
{ path: '/:product', component: Product, beforeEnter: productExists },
{ path: '*', name: 'notFound', component: NotFoundException }
]
I'm trying to put a router that is imported as a constant in main router`s children
router/components/slider/index.js:
const sliderRouter = {
path: '/slider',
name: 'Slider',
meta: {
title: 'Slider'
},
component: () => import('#/views/components/slider'),
}
export default sliderRouter
router/index.js:
...
import authRouter from './modules/auth'
import sliderRouter from './modules/components/slider'
...
export default new Router({
mode: 'history',
linkActiveClass: "active selected",
routes: [
authRouter, // this work
{
path: '/admin',
name: 'primary',
meta: { requiresAuth: true },
// remastered version
component: loadView('MainLayout'),
children: [
sliderRouter, /* make something like this */
//recent routes
{
path: '/home',
name: 'home',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
// classic version:
component: () => import(/* webpackChunkName: "about" */ '../views/Home.vue')
// component: About
}
]
},
Is it really possible to make the slider router work in such way and inherit from the MainLayout (like a typical child), and also URL would be '/admin/slider'?
I solved it by changing the path in the slider
path: '/slider',
to
path: 'slider',
because it is using like child route which does not require a slash before it`s name
I have an issue with a default children route in Vue.js 2.
When I visit localhost/listings initially, it correctly loads index.vue and map.vue as a child.
When I navigate using router-link to localhost/listings/1, and then using router-link back to localhost/listings, then it still loads the show.vue template. This shouldn't happen?
I have no navigation guards or anything that should interfere. Is there anyway to correct this?
My routes:
window.router = new VueRouter({
routes: [
...
{
path: '/listings',
name: 'listing.index',
component: require('./components/listing/index.vue'),
children: [
{
path: '',
component: require('./components/listing/map.vue')
},
{
path: ':id',
name: 'listing.show',
component: require('./components/listing/show.vue')
}
]
},
...
]
});
The "father" router should not be named if you want a default child route, so instead using :to="{name: 'listing.index'}", use the name of the default child route (e.g :to="{name: 'listing.map'}").
The code should look like this:
window.router = new VueRouter({
routes: [
...
{
path: '/listings',
component: require('./components/listing/index.vue'),
children: [
{
path: '',
name: 'listing.map'
component: require('./components/listing/map.vue')
},
{
path: ':id',
name: 'listing.show',
component: require('./components/listing/show.vue')
}
]
},
...
]
});
Maybe try re-arranging the children, routes are fired in the order they match from top-to-bottom, so this should hopefully fix it:
window.router = new VueRouter({
routes: [
...
{
path: '/listings',
name: 'listing.index',
component: require('./components/listing/index.vue'),
children: [
{
path: ':id',
name: 'listing.show',
component: require('./components/listing/show.vue')
}
{
path: '',
component: require('./components/listing/map.vue')
},
]
},
...
]
});
Just for a bit of clarification, your path: '' essentially serves as a "catch all", which is likely why when it's at the top it's being found immediately and so the router never propagates any further down to the :id route.
In Vue 2.6.11 you can automatically redirect to a child route if parent route is hit:
const routes = [
{
name: 'parent',
path: '/',
component: Parent,
children: [
{
name: 'parent.child',
path: 'child',
component: Child,
}
],
/**
* #type {{name: string} | string} Target component to redirect to
*/
redirect: {
name: 'parent.child'
}
}
];
When you are using named routes and you want to load the component with your child inside, you have to use the name route for the child.
In your Navigation menu links, if you use name route for the parent, the child will not load automatically, even if the child path is nothing.
Let's say for example we have a User route, and we want to show list of users inside the component by default so whenever we go to '/user' path we want to load a list of users as a child in there:
routes: [
{
path: '/user',
name: 'User',
component: User,
children: [
{path: '', name: 'UserList', component: UserList}, // <== child path is = '';
]
}
]
If you think about the code, you might assume if you go to route with name 'User' you might get UserList in there as well, because the path for parent and children both are same. but it's not and you have to choose 'UserList' for the name.
Why this is happening?
Because Vuejs loads the exact component you are referring to, not the url.
you can actually test this, instead of using named route in your links, you can just refer the url, this time vuejs will load the parent and child together with no problem, but when you use named route, it doesn't look at the url and loads the component you are referring to.