Dynamic layout in Vue 3 with Vite

Viewed 3855

New to Vue and Vite but trying to get dynamic layouts working properly here. I believe I have what is needed but the issue it the meta seems to always come up as an empty object or undefined.

AppLayout.vue

<script setup lang="ts">
  import AppLayoutDefault from './stub/AppLayoutDefault.vue'
  import { markRaw, watch } from 'vue'
  import { useRoute } from 'vue-router'

  const layout = markRaw(AppLayoutDefault)
  const route = useRoute()

  console.log('Current path: ', route.path)
  console.log('Route meta:', route.meta)

  watch(
    () => route.meta,
    async (meta) => {
      try {
        const component = await import(`./stub/${meta.layout}.vue`)
        layout.value = component?.default || AppLayoutDefault
      } catch (e) {
        layout.value = AppLayoutDefault
      }
    },
    { immediate: true }
  )
</script>

<template>
  <component :is="layout"> <router-view /> </component>
</template>

App.vue

<script setup lang="ts">
  import AppLayout from '@/layouts/AppLayout.vue'
</script>
<template>
  <AppLayout>
    <router-view />
  </AppLayout>
</template>

Each and every route has the appropriate meta set with a property called layout.

I just can't seem to get he layout applied correctly on the first load or any click of a link in the navbar(which are just router-link) for that matter.

1 Answers

The main problem is layout is initialized as markRaw(), which is not a reactive ref:

const layout = markRaw(AppLayoutDefault) // ❌ not reactive

Solution

  1. Initialize layout as a ref.
  2. Instead of watching the full route object, watch route.meta?.layout because that's the only relevant field for the handler.
  3. Wrap layout's new values with markRaw() to avoid reactivity on the component definition.
const layout = ref() 1️⃣

watch(
  () => route.meta?.layout as string | undefined, 2️⃣
  async (metaLayout) => {
    try {
      const component = metaLayout && await import(/* @vite-ignore */ `./${metaLayout}.vue`)
      layout.value = markRaw(component?.default || AppLayoutDefault) 3️⃣
    } catch (e) {
      layout.value = markRaw(AppLayoutDefault) 3️⃣
    }
  },
  { immediate: true }
)

demo

Related