Remove existing routes #1234
Remove existing routes #1234
Comments
Why would you ever need to delete a created route without adding a new one replacing it? |
In my app user may dynamically set routing. For example he has three predefined components A, B and C; In the application (in browser :) he can manage route configuration; let's say there is a textarea with following JSON: [{ path: "/my-custom-path", component: "A" }, { path: "/some/other/path/:id", component: "B" }, ...] For now I can just add new routes to the router: import A from '@/components/A';
import B from '@/components/B';
import C from '@/components/C';
const allComponents = { A, B, C };
// "routes" is array of routes provided by user/client in textarea (textarea is just an example :).
onConfigChanged = routes => {
routes = routes.map(route => {
return { path: route.path, component: allComponents[route.component] };
});
router.addRoutes(routes);
};
// onConfigChanged is called on each change to configuration by user/client What I need is to completely replace all routes: #1129 is close but it won't solve my problem because I don't know route names... I know that this is not primary use-case for VueRouter, but it would allow to do more advanced things (like my use-case). |
I like this feature request, I have uses cases where I need to replace url parameters dynamically just to generate a URL to share and grant a unique access for a view with data that I already have in memory (where I don't need view changes or async operations). |
My application has different very routes for different user roles (some are replaced, some should be inaccessible or not exist at all). While it is already possible to achieve this using hooks and basic permissions definitions, I am interested in the idea of replacing the routes entirely on login/logout. The set of routes available could then be unique for each user role, and public/non-authenticated users. |
I had my (the +1 for dynamic routes config, so I can export the router instance first. |
'replaceRoutes' method replaces all routes in router close vuejs#1234
Is there any intention of implementing this? It felt like there was some momentum on this for a while |
My use case: Modular app, where you enable/disable modules (basically separate components, pages) that have pre-configured routes. Adding a route after enabling a module is ok, but when disabling module, previous routes need to be removed. |
I agree this is needed. Imagine you implement a landing page that loads various apps dynamically, so that each app loaded would want to clear any previously loaded routes and load its own in. Also imagine that this information is sent up from the server dynamically. This seems like a simple api of router.removeRoutes ([routeKeys]) or empty array to remove all. |
The case for authorization-based (or capability-based) route definitions seems to be very common for sufficiently sophisticated apps. In my case (somewhat similar to @nickforddesign's), I'd love to be able to start with a minimal set of public routes for unauthenticated users, and if they try to access any of the protected routes they get a 404 (or maybe redirected to login). Upon login, the server would respond with a list of accessible routes based on the current user role and/or app configuration. |
All interceptors and authentications can be implemented with |
@JounQin Please consider a client side plugin system that allows individual plugins to be disabled/enabled. When enabled, the routes provided by the plugin must be added to the system. When disabled, these routes need to be removed again in order for the application to fail consistently, namely with a 404 instead of continuing to render the components/views associated with that route. An alternative, of course, would be to implement a beforeEnter hook which checks whether the route is available and redirecting to 404 instead when it is not. |
@limoli I had the same issue and solved it by replacing the router's
|
I'm really keen on having this feature. My app dynamically loads/unloads content, so if I unload a module, it'd be fantastic if it's be easy to unlink the routes (and redirect to my 404 or home page). |
@coxy great~ it works~ |
I have similar problem: I have many minis app with its routes: Content app, User app. My goal is:
Below my code:
MINI APPS EXPORT (dynamicImports/Content):
what do you think of this solution? |
to replace router matcher to implement dynamic routes deletion vuejs/vue-router#1234 (comment)
Here's a very dirty function to append new child routes. I'm hoping the dirtiness of it encourages the maintainers to come up with a better solution. Keep in mind the My use case was entirely appending new child routes to a parent route that handled global data preloading and authentication based on authenticated user's permissions. I can neither confirm nor deny whether or not this was put into production. export default function appendRoutes(router, newRoutes) {
const existingRoutes = router.options.routes;
newRoutes.forEach( (newRoute) => {
// try to find an existing route based on the path
let existingRoute = existingRoutes.find(r => r.path === newRoute.path);
// if the specific route path already exists, then try to merge the children
if(existingRoute && newRoute.children && newRoute.children.length) {
// ensure type
existingRoute.children = existingRoute.children || [];
// append the new children
existingRoute.children.push(...newRoute.children);
// suppress duplicate route warnings to quiet logs during development
const warn = console.warn;
console.warn = () => {};
router.addRoutes([existingRoute])
console.warn = warn;
}else{
router.addRoutes([moduleRoute])
}
})
} |
I give another usage example of deleting/replacing routes. So the flow is the following :
|
My use case is a user can create, edit, and delete routes with configurations for a configurable component that would come in through the API and would be added at runtime. When I add, remove, reorder routes I get the duplication routes warning. |
I don't understand why And I tried to add a few more const reset = () => {
router.matcher = createRouter().matcher
// Here's how to try it out
router.addRoutes([...])
// or
router.options.routes = [...]
} Why is there only one official The result is still not effective, but I feel that My problem this should be caused by the following problem. asterisk(*) must be placed at the end Generally, the initial router has |
this is my code , success!!! export function resetRouter() { |
fail to use reset method with "router.matcher = newRouter.matcher" like @coxy |
So @coxy method doesn't work anymore in the latest vue-router? PS. I just tried - it works fine. |
My apps are also authorisation-based and I would want to be able to enable/disable routes depending on signed-in/signed-out state. I will also be working on an app where modules are dynamically enabled or disabled, which means routes to them will need to be switched on and off for them as well. I can find workarounds but in my view this should be solved in the router itself. It feels strange that it's only possible to add routes, never remove or rewrite them. |
How this is fixed in 4.0? I don't see it implemented anywhere. I'm also looking for a way to remove existing route and replace route functionality. |
Also looking for this feature. Developing an app where the user and enable/disable modules, and each module has its own routes. Ideally when unloading a module the related routes should be disabled (so user goes to 404 instead of a non-functional component if they try to access it). If we already have addRoutes() surely adding a clear() or a remove() should be a trivial new feature to add.. ? |
Why do you need a delete routing feature? your
When a user logs into your web application with an account and password, he or she immediately requests a menu data from the server, which you then consolidate into your local router area using addRouter :
|
My users also logout. I need to reset the routes to the logged-out state after that. I have another use case where users can create and delete objects which map to routes in the UI. The server also notifies the UI if another user in the same group has made these types of changes. I.e. the routes need to be dynamically updated through user actions. |
Hi, It consists on checking the path on the url against the routes of the router. In the App.vue:
Cheers, |
This comment has been hidden.
This comment has been hidden.
Another usecase: oversimplifying a lot for demo purposes but let's say that I have basically 2 apps running while migrating a codebase: // inital router.js
const routes = [...alreadyMigratedNextRoutes] // already battle-tested vue routes no longer under the featureFlag, no more legacy views fallback
const router = new VueRouter({ routes })
// some data fetching work...
if (store.state.curAccount.featureFlag) {
router.addRoutes(underTestingNextRoutes) // the ones with the same paths as legacy views, now curAccount will get `next` views
}
// else do nothing (as in navigating to those paths will load the `legacy` app versions
// voilá this works The problem is that switching accounts on the app (meaning no page reload) and assuming // pseudoCode for some selectbox
onSwitchAccounts(targetAccount) {
this.$store.dispatch('fetchAccount', targetAccount).then((accountBPayloadj) => {
this.$store.commit('UPDATE_CUR_ACCOUNT', accountBPayload)
if (accountBPayload.featureFlag === false) {
// yup would be handy
this.$router.removeRoutes(underTestingNextRoutes)
// Now if accountB goes to `myapp.com/some-page`, it should see the `legacy` version.
}
})
}
Does this make sense on why I can't simply use router hook/guard? In practice i want to redirect... to the same url. Note that i'm not saying there isn't another way of doing it, and yes "you should just use a |
@posva It says you added |
@redfox05 it's here: https://github.com/vuejs/vue-router-next for Vue 3 |
@posva Thanks, was hoping for a commit hash or link to documentation, but understand you're probably busy. For others interested in the information, I managed to find the docs for it here: https://next.router.vuejs.org/guide/advanced/dynamic-routing.html#removing-routes I was surprised this issue was not linked to a commit when the feature was implemented, and this issue is still Open, so figured it was not fully complete? Hence I tried looking for a commit hash but couldn't find one. Hopefully the docs will be enough for people. |
Right now it is possible to dynamically add routes by calling
router.addRoutes([/* routes */])
. It would be nice if it was possible to also remove/replace routes on the fly. In my app user may define routes by himself (on the fly). I keep user configuration in the Vuex store, and when it is updated I want to completely replace whole router routes configuration (though replacing/removing single route would be also handful but I guess then it should also handle removing/replacing/adding child routes instead of only dealing with top-level routes, which would be quite complicated). I imagine that after replacing routes router would check if current path matches any of the new routes and navigated to it.It could be for example method
router.replaceRoutes([/* routes */])
orrouter.setRoutes
(in addition to methodrouter.addRoutes
which already exists).Please note that this situation can be handled without VueRouter by setting one global route
/*
that will match every possible path, performing route matching inside this global route component (based on dynamic config stored in Vuex store for example) and dynamic rendering of component(s) that matched current path. However this is very ugly solution which looses all benefits of VueRouter, and handling child routes would be complicated.In fact I wanted to handle it by patching VueRouter manually, but it seems that
createMatcher
(https://github.com/vuejs/vue-router/blob/dev/src/create-matcher.js#L16) does not exposepathMap
andnameMap
so it is not possible modify routes configuration in other way than by callingrouter.addRoutes
(I guess it's intentional :).The text was updated successfully, but these errors were encountered: