Only add linkExactActiveClass in specific layout and page

Viewed 48

I'm relatively new to Vue. I have a multi-layout on my app, but only one router.

I followed this tutorial for context. I want to only add active classes on a specific layout and page. For example, I only want active classes on the admin layout navigation, not on the landing page layout navigation. How do I achieve this?

main.js

import { createApp } from "vue";
import App from "./App.vue";
import { routes } from "./routes.js";
import { createRouter, createWebHistory } from "vue-router";

const app = createApp(App);

const router = createRouter({
  history: createWebHistory(),
  routes,
  linkExactActiveClass: "active",
});

app.use(router);
app.mount("#app");

routes.js

import Home from "./views/Home.vue";

import Dashboard from "./views/app/Dashboard.vue";

export const routes = [
  {
    path: "/",
    component: Home,
    meta: { layout: "LandingLayout", title: "Home" },
  },
  {
    path: "/user",
    component: Dashboard,
    meta: { layout: "AppLayout", title: "Dashboard" },
  },
];

App.vue

<template>
  <component :is="layout" />
</template>

<script>
import LandingLayout from "@/layouts/LandingLayout.vue";
import AdminLayout from "@/layouts/AdminLayout.vue";

export default {
  components: {
    LandingLayout,
    AdminLayout,
  },
  data() {
    return {
      layout: null,
    };
  },
  watch: {
    $route(to) {
      if (to.meta.layout !== undefined) {
        this.layout = to.meta.layout;
      } else {
        this.layout = "LandingLayout";
      }
    },
  },
};
</script>

Any help would be much appreciated.

1 Answers

You were pretty close. The only thing you forgot was to make the route watch happen immediately by providing it like this:

  watch: {
    $route: {
      immediate: true,
      handler(to) {
        if (to.meta?.layout) {
          this.layout = to.meta.layout;
        } else {
          this.layout = "LandingLayout";
        }
      },
    },
  },

and then you can just change the this.$router.options.linkExactActiveClass option dynamically like this:

$route: {
      immediate: true,
      handler(to) {
        if (to.meta?.layout) {
          this.layout = to.meta.layout;
          this.$router.options.linkExactActiveClass = `my-active-link-other-layout`;
        } else {
          this.layout = "LandingLayout";
          this.$router.options.linkExactActiveClass =
            "my-active-link-landing-layout";
        }
      },
    },

See it in action:

Codesandbox link

Related