vue-router icon indicating copy to clipboard operation
vue-router copied to clipboard

Remove existing routes

Open alekbarszczewski opened this issue 7 years ago • 44 comments

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 */]) or router.setRoutes (in addition to method router.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 expose pathMap and nameMap so it is not possible modify routes configuration in other way than by calling router.addRoutes (I guess it's intentional :).

alekbarszczewski avatar Mar 09 '17 13:03 alekbarszczewski

Why would you ever need to delete a created route without adding a new one replacing it? I think you may be interested in #1129

posva avatar Mar 09 '17 13:03 posva

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: router.replaceRoutes(routes) or maybe router.addRoutes(routes, { replace: true }) (it should completely replace routes configuration).

#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).

alekbarszczewski avatar Mar 09 '17 13:03 alekbarszczewski

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).

ianaya89 avatar Mar 17 '17 01:03 ianaya89

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.

nickforddev avatar Apr 12 '17 17:04 nickforddev

I had my components depends on the api, and the api now needs to depend on the router, however, the router has to depend on the components, because of the new Router({ routes: [{ component }] }) syntax, which causes a circular require now.

(the resolve => reuqire([path], resolve) syntax doesn't work for me.)

+1 for dynamic routes config, so I can export the router instance first.

fritx avatar Jul 01 '17 11:07 fritx

Is there any intention of implementing this? It felt like there was some momentum on this for a while

nickforddev avatar Sep 26 '17 15:09 nickforddev

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.

frenchbread avatar Dec 01 '17 14:12 frenchbread

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.

goldenram avatar Dec 07 '17 17:12 goldenram

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.

khaledh avatar Dec 28 '17 23:12 khaledh

All interceptors and authentications can be implemented with beforeEach hook, I still don't understand why you need add or replace routes dynamic.

JounQin avatar Dec 29 '17 00:12 JounQin

@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.

silkentrance avatar Dec 29 '17 17:12 silkentrance

@posva

Why would you ever need to delete a created route without adding a new one replacing it? I think you may be interested in #1129

How could you implement this? Is it possible to create a new Router and assign it to the main app Router?

limoli avatar Jan 03 '18 14:01 limoli

@Limoli I had the same issue and solved it by replacing the router's matcher object with one from a newly created router instance.. something like:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const createRouter = () => new Router({
  mode: 'history',
  routes: []
})

const router = createRouter()

export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // the relevant part
}

export default router

coxy avatar Jan 16 '18 12:01 coxy

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). Edit: Router guards can work, but this would be much easier because I wouldn't need to have like 20 guards in place to accommodate all my separate modules... Oh, and I don't think we can dynamically add router guards?

xon52 avatar Jan 24 '18 06:01 xon52

@coxy great~ it works~

JesseZhao1990 avatar Mar 15 '18 09:03 JesseZhao1990

I have similar problem: I have many minis app with its routes: Content app, User app. A main app, used and load these mini apps. Main app load mini app asynchronously.

My goal is:

  1. User wants to go "content/details/video_1"
  2. Main app seeing the hash, knows that users wants to use mini app "Content". So, mini app "Content" and its routes are loaded?
  3. If no, ok loaded component, apply routes and finally show the component

Below my code: MAIN APP Router code:

import Vue from "vue";
import Router from "vue-router";
import HelloWorld from "@/components/HelloWorld";

Vue.use(Router);

const loadSection = function(to, next) {
	//Load Content section:
	if (to.includes("/content")) {
		let promiseContent = import("dynamicImports/Content");
		promiseContent.then(
			(contentItem) => {
				contentItem = contentItem.default;
				//call init mini app (add routes mini app):
				contentItem.init(router);
				//After apply mini app routes, i must to force next(to)
                                //instead of next(). next() do nothing... bug???
                                 next(to);
			}
		);
	} else {
		next();
	}
};


const router = new Router({
	routes: [
		{
			path: "/",
			name: "HelloWorld",
			component: HelloWorld
		}
	]
});

router.beforeEach((to, from, next) => {
	if (router.match(to.path).matched.length === 0) {
		loadSection(to.path, next);
	} else {
		next();
	}
});

export default router;

MINI APPS EXPORT (dynamicImports/Content):

import RouterConfig from "router";
import MainApp from "components/app.vue";
import ContentDet from "components/contentDetails/ContentDetails.vue";

export const App = {
	component: MainApp,
	init: function(router:any) {
		//Add routes:
		router.addRoutes(RouterConfig);
	}
};

what do you think of this solution?

ale-grosselle avatar May 04 '18 19:05 ale-grosselle

Similar problem to me as the complex system has many different roles and authorizations. Instead of adding security check to each root components and do conditional rendering, it is better to have access control in the router level. In addition, it makes no sense to let the user access the route if they can see nothing there.

Thanks for @coxy 's patch, but we still need the official methodology to address this problem as this patch might not work after library upgrade. (And the complain from Tslint)

Please, Please, Please

Ps: it's interesting that Vue-router ONLY have addRoute method there, it makes me feel like I can only add money to wallet while I never get a chance to spend them ;)

johnny-dash avatar Aug 03 '18 04:08 johnny-dash

为什么不将createMatcher方法放开,这样这个router里面的matcher不是可以自己生成,动态修改起来也方便,动态修改routeList不是也很方便

wangqiang66 avatar Oct 18 '18 08:10 wangqiang66

In my use case, where routes should be loaded depending on the role of a user, this feature would be really helpful.

emielmolenaar avatar May 23 '19 07:05 emielmolenaar

Very needed function to delete already registered routes. On my site different users has different allowed URLs to go. If user login or logout some routes blockes, some opens.

But now there is no system of deleting or updating exiting routes.

I think there need to be functality to iterate throw all routes with an ability to delete any route or update it.

DmitrijOkeanij avatar May 28 '19 09:05 DmitrijOkeanij

another usecase: i'am currently using laravel nova which is heavily based on Vue - which is nice, but in case someone wants to overwrite some of the provided views, there's no other way as to replace the whole router, which is kind of silly. Single components are no problem as Vue.component(); can replace existing components, but that's currently not possible with Views which are hardcoded in the Nova routing configuration.

Would be nice if addRoutes() would simply replace duplicate routes (just as Vue.component does), at least the named ones.

Etmolf avatar Jun 23 '19 01:06 Etmolf

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 console.warn suppresses ALL warnings when adding the routes and that to handle all cases you'll need an additional if statement or two. This has some clear problems if you try to update a named route because vue-router refuses to overwrite the named route reference :man_facepalming:; but, adding the same named route multiple times doesn't seem to cause any problems.

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. :worried:

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])
    }
  })
}

Aaron3 avatar Aug 30 '19 07:08 Aaron3

I give another usage example of deleting/replacing routes. In an app, I use routes to switch pages, all with the same component, changing content. Pages are loaded from an api so routes can change (added/modified/deleted) because the user can change the page name that can be seen in the URL thanks to router.

So the flow is the following :

  1. app startup, only login and register routes are available if there is no authentication yet
  2. when authenticated, pages are loaded from rest service
  3. I rebuild routes based on available pages, plus the static ones (logout, login, etc...) 4a) user creates a new page (so a new route) 4b) user deletes a page (so route should not be available anymore 4c) user changes page name, equals deleting the route with old name, and adding a new one
  4. user has a default page, / route redirects to it and of course, they can change their default page :)

riri avatar Sep 18 '19 20:09 riri

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.

dannynpham avatar Oct 11 '19 17:10 dannynpham

I don't understand why router.matcher = createRouter().matcher would have so many people agree, at least I did not succeed. vue 2.6.10, vue-router 3.1.2

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 addRoutes([]), even if it gives one more clear(), otherwise there will be a lot of duplicate routing warnings when adding?

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 * => 404. As a result, the route added by the subsequent router cannot be routed at all, so it can be solved by refreshing the page and creating again.

liuanxin avatar Dec 04 '19 11:12 liuanxin

this is my code , success!!!

export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher // reset router router.options.routes = [] }

lugging avatar Jan 13 '20 12:01 lugging

fail to use reset method with "router.matcher = newRouter.matcher" like @coxy I lost all my router after reset, it seem dont't work :(

Jiny3213 avatar Jan 18 '20 14:01 Jiny3213

So @coxy method doesn't work anymore in the latest vue-router?

PS. I just tried - it works fine.

dmitry avatar Feb 04 '20 10:02 dmitry

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.

brikoleur avatar Feb 17 '20 07:02 brikoleur

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.

davispuh avatar Apr 11 '20 20:04 davispuh