This is the first day of my participation in the wenwen Challenge

Recently, the technology stack of the company has been adjusted, and we decided to use Vue3 and TypeScript to develop background management. After completing the project, we started to do dynamic routing. I hope to make a summary and bring help to you!

The back end returns the following structure:

The structure returned by the back end is the permission list and menu list, and the front end performs recursive comparison and elimination according to the permission list and the local route list that has not been loaded. In the permission list/It starts with routing_The first is whether the elements of the page are operable

Create a route elimination class

class filterRouteList {
    private auth: string[];
    constructor( options: string[] ) { 
        this.auth = options;
        this.init();
    }
    init() {
        
    }
}

export default filterRouteList;
Copy the code

After successful login, this class will be called to filter the route auth receive permission list;

if ( res.code === 0 ) {
    new filterRouteList( res.data.auth )
}
Copy the code

At this point, the init function is called to initialize and the TreeFilter function is called to filter

init() { const routelist = TreeFilter( this.auth ); This.renderrouter (routelist)} TreeFilter(arr: any) {// auth format is: ['/home','/setting'] let rep: any = []; arr.forEach( ( item: any ) => { if ( this.auth.indexOf( item.path ) ! = -1 ) { if ( item.children && item.children.length > 0 ) { item.children = this.TreeFilter( item.children ); } rep.push( item ) } }) return rep; }Copy the code

The ARR is a route configured locally but not yet written into the route.

  • Traversing the tree route and routing each itempathCompare this to a permission list, for example:'/home' === '/home', if it can be found and there are child nodes, the recursion is carried out, and the routes that are removed are finally writtenrep, the filtered routes are as follows:

RenderRouter is then called to write the route

renderRouter( route: object[] ) {
    route.forEach( ( item: any ) => {
        router.addRoute( 'gulp', {
            path: item.path,
            component: item.component,
            meta: item.meta,
            children: item.children
        })
    })
}
Copy the code

Vue2 is addRoutes but changed to addRoute in vue3. We only need to pass through the filtered route and call addRoute according to the corresponding fields to realize the dynamic route.

conclusion

That’s all for this article. If you happen to be working on this requirement, please refer to a few of them. I hope these experiences will help you!