[Vuejs]-How to pass data and events between named views in Vue Router?

0đź‘Ť

Here is an approach I came to. It is far from ideal but at least it works and allows me to keep state where it should belong.

First, I created a BaseTemplate component which contains most of the markup of the app. I.e. the App component holds just a bare minimum, and most of the body (including immutable parts) is moved to BaseTemplate:

// BaseTemplate.vue
<template>
<div>
  <header>
    <slot name="title">{{ title }}</slot>
    <slot name="controls"/>
  </header>
  <nav>
    <router-link ...>
    <router-link ...>
  </nav>
  <main>
    <slot/>
  </main>
</div>
</template>

<script>
export default {
  props: ['title'],
};
</script>
// Tab1.vue
<template>
  <BaseTemplate title="First Tab">
    <template #controls>
      ...
    </template>

    main content goes here...
  </BaseTemplate>
</template>
...

This way, all props related to Tab1 belong to Tab1 component, and at the same time common markup is moved to the separate component.

Now to the downsides.
Unlike the “normal” setup where common controls/navigations are outside the route-view, in this setup they are in fact different component instances for each tab. So they blink when switching.
Not sure if it can be mitigated somehow.

Leave a comment