All files router-view.ts

94.73% Statements 18/19
80% Branches 4/5
100% Functions 1/1
94.73% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601x 1x 1x                                                           1x 1x 1x 29x       29x   29x     40x     40x 40x         40x 38x 2x 40x 29x 1x  
import { defineComponent, h } from 'vue';
import { _useRouterViewDepth, useRoute } from './use';
import { resolveComponent } from './util';
 
/**
 * RouterView component for rendering matched route components.
 * Acts as a placeholder where route components are rendered based on the current route.
 * Supports nested routing with proper depth tracking using Vue's provide/inject mechanism.
 *
 * @param props - Component properties (RouterView accepts no props)
 * @param context - Vue setup context (not used)
 * @param context.slots - Component slots (not used)
 * @returns Vue render function that renders the matched route component at current depth
 *
 * @example
 *
 * ```vue
 * <template>
 *   <div id="app">
 *     <!-- Navigation links -->
 *     <nav>
 *       <RouterLink to="/">Home</RouterLink>
 *       <RouterLink to="/about">About</RouterLink>
 *       <RouterLink to="/users">Users</RouterLink>
 *     </nav>
 *
 *     <!-- Root level route components render here -->
 *     <RouterView />
 *   </div>
 * </template>
 * ```
 */
export const RouterView = defineComponent({
    name: 'RouterView',
    setup() {
        const route = useRoute();
 
        // Get current RouterView depth and automatically provide depth + 1 for children
        // This enables proper nested routing by tracking how deep we are in the component tree
        const depth = _useRouterViewDepth(true);
 
        return () => {
            // Get the matched route configuration at current depth
            // route.matched is an array of matched route configs from parent to child
            const matchedRoute = route.matched[depth];
 
            // Resolve the component, handling ES module format if necessary
            const component = matchedRoute
                ? resolveComponent(matchedRoute.component)
                : null;
 
            // Render the component with compilePath as key to force re-render when route config changes
            // Using compilePath ensures component is recreated when navigating to different route configs
            return component
                ? h(component, { key: matchedRoute.compilePath })
                : null;
        };
    }
});