Skip to content

viewDepthKey | Vue Router - Advanced Router View Control ๐Ÿ”ง โ€‹

Fine-grained view management - Control which nested component gets rendered in complex routing scenarios!

๐ŸŽฏ Variable Overview โ€‹

viewDepthKey is an advanced injection key that allows you to override the router view depth, giving you precise control over which component in the matched route hierarchy gets rendered. This is particularly useful for complex nested routing scenarios.

๐Ÿ“‹ Basic Usage โ€‹

typescript
const viewDepthKey: InjectionKey<number | Ref<number, number>>

๐Ÿ’ก When to Use viewDepthKey โ€‹

๐ŸŽฏ Complex Nested Routing โ€‹

Use viewDepthKey when you need to:

  • Override Default Behavior: Control which nested component renders
  • Dynamic View Selection: Change rendered components based on application state
  • Advanced Layout Management: Implement complex multi-level layouts

๐Ÿ”ง Technical Implementation โ€‹

typescript
import { viewDepthKey } from 'vue-router'

// Provide a custom view depth
provide(viewDepthKey, 2) // Render the component at depth 2

๐Ÿ› ๏ธ Practical Examples โ€‹

Example 1: Basic Depth Control โ€‹

vue
<template>
  <div class="app-container">
    <!-- Default RouterView behavior -->
    <RouterView />
    
    <!-- Custom depth RouterView -->
    <RouterView :depth="customDepth" />
  </div>
</template>

<script setup>
import { ref, provide } from 'vue'
import { viewDepthKey } from 'vue-router'

const customDepth = ref(2)

// Override view depth for this component tree
provide(viewDepthKey, customDepth)
</script>

Example 2: Dynamic View Switching โ€‹

vue
<template>
  <div class="multi-level-app">
    <!-- Navigation controls -->
    <div class="depth-controls">
      <button @click="decreaseDepth">โฌ…๏ธ Previous Level</button>
      <span>Current Depth: {{ currentDepth }}</span>
      <button @click="increaseDepth">Next Level โžก๏ธ</button>
    </div>
    
    <!-- RouterView with dynamic depth -->
    <RouterView />
  </div>
</template>

<script setup>
import { ref, computed, provide } from 'vue'
import { viewDepthKey, useRoute } from 'vue-router'

const route = useRoute()
const currentDepth = ref(0)

// Calculate maximum available depth
const maxDepth = computed(() => {
  return route.matched.length - 1
})

function increaseDepth() {
  if (currentDepth.value < maxDepth.value) {
    currentDepth.value++
  }
}

function decreaseDepth() {
  if (currentDepth.value > 0) {
    currentDepth.value--
  }
}

// Provide dynamic depth control
provide(viewDepthKey, currentDepth)
</script>

<style scoped>
.depth-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

button {
  padding: 0.5rem 1rem;
  border: 1px solid #007bff;
  background: white;
  color: #007bff;
  border-radius: 4px;
  cursor: pointer;
}

button:hover:not(:disabled) {
  background: #007bff;
  color: white;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

๐Ÿ” Technical Details โ€‹

๐Ÿ”„ How View Depth Works โ€‹

Vue Router uses view depth to determine which component to render in nested routing scenarios:

Route: /users/123/posts/456/comments

Matched Components:
- Depth 0: UserLayout
- Depth 1: UserProfile
- Depth 2: UserPosts  
- Depth 3: PostComments

By default, RouterView renders the component at the current depth.
viewDepthKey allows you to override this behavior.

โšก Injection Key Type โ€‹

typescript
// The injection key accepts numbers or reactive references
type ViewDepth = number | Ref<number>

// Usage examples
provide(viewDepthKey, 2)                    // Static depth
provide(viewDepthKey, ref(2))               // Reactive depth
provide(viewDepthKey, computed(() => ...))  // Computed depth

๐ŸŽฏ Advanced Usage Patterns โ€‹

Pattern 1: Conditional Rendering โ€‹

typescript
import { viewDepthKey, useRoute } from 'vue-router'
import { computed, provide } from 'vue'

const route = useRoute()

// Only show specific depths based on route parameters
const dynamicDepth = computed(() => {
  if (route.params.showDetails) {
    return 2 // Show detailed view
  }
  return 1 // Show summary view
})

provide(viewDepthKey, dynamicDepth)

Pattern 2: Multi-level Navigation โ€‹

vue
<template>
  <div class="wizard-container">
    <!-- Progress indicator -->
    <div class="wizard-progress">
      <div 
        v-for="step in totalSteps" 
        :key="step"
        class="progress-step"
        :class="{ active: currentStep >= step }"
        @click="goToStep(step)"
      >
        Step {{ step }}
      </div>
    </div>
    
    <!-- Dynamic RouterView -->
    <RouterView />
  </div>
</template>

<script setup>
import { ref, provide, computed } from 'vue'
import { viewDepthKey } from 'vue-router'

const currentStep = ref(1)
const totalSteps = 4

// Use step as view depth
provide(viewDepthKey, currentStep)

function goToStep(step) {
  if (step <= totalSteps) {
    currentStep.value = step
  }
}
</script>

๐Ÿš€ Performance Considerations โ€‹

โšก Optimized Re-rendering โ€‹

typescript
// Use computed properties for optimal performance
const optimizedDepth = computed(() => {
  // Only recalculate when dependencies change
  return someCondition ? 2 : 1
})

provide(viewDepthKey, optimizedDepth)

๐Ÿ”„ Memory Management โ€‹

typescript
import { onUnmounted } from 'vue'

// Clean up when component unmounts
onUnmounted(() => {
  // Reset to default behavior if needed
  provide(viewDepthKey, undefined)
})
  • RouterView - The component that uses view depth
  • matchedRouteKey - Key for accessing the current route record
  • routeLocationKey - Key for accessing the current route location

๐Ÿ”ง Integration Examples โ€‹

With Vuex/Pinia โ€‹

typescript
import { useStore } from 'vuex'
import { viewDepthKey } from 'vue-router'
import { computed } from 'vue'

const store = useStore()

// Use store state to control view depth
const viewDepth = computed(() => store.state.ui.viewDepth)

provide(viewDepthKey, viewDepth)

With TypeScript โ€‹

typescript
import { viewDepthKey } from 'vue-router'
import { Ref, inject } from 'vue'

// Type-safe injection
const depth = inject<Ref<number>>(viewDepthKey)

if (depth) {
  depth.value = 2 // Safe assignment
}

๐Ÿ’ก Pro Tip

Use viewDepthKey in combination with route meta fields to create intelligent view switching based on user permissions or application state!

Ready for advanced routing control? Start using viewDepthKey to master complex nested routing scenarios! ๐Ÿ”ง

๐Ÿš€ Vue Router - ่ฎฉๅ‰็ซฏ่ทฏ็”ฑๅ˜ๅพ—็ฎ€ๅ•่€Œๅผบๅคง | ๆž„ๅปบ็ŽฐไปฃๅŒ–ๅ•้กตๅบ”็”จ็š„ๆœ€ไฝณ้€‰ๆ‹ฉ