Script in Nuxt Single Page App don't work

Viewed 49

I have a project with Nuxt.js and I want to execute this code into all the page of the project (it serves to underline the page where you are in the menu):

if (window.location.pathname == "/") {
  actualPage = document.querySelector(".accueil");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

if (window.location.pathname == "/tous-les-articles") {
  actualPage = document.querySelector(".tous-les-articles");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

if (window.location.pathname == "/sciences") {
  actualPage = document.querySelector(".sciences");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

if (window.location.pathname == "/actualites") {
  actualPage = document.querySelector(".actualites");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

if (window.location.pathname == "/histoire") {
  actualPage = document.querySelector(".histoire");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

if (window.location.pathname == "/livres") {
  actualPage = document.querySelector(".livres");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

if (window.location.pathname == "/le-saviez-vous") {
  actualPage = document.querySelector(".le-saviez-vous");
  actualPage.removeAttribute("id");
  actualPage.setAttribute("id", "active");
}

When I directly go to the page, it work.

But the problem is that when I navigate with the menu to go to another page, it don't work. My project is in Single Page App.

I already tried to create a new project in Universal, but it didn't work as well.

1 Answers

Instead of using javascript to get your current route name & adding css to it, as you are using nuxt js you can use vue $route.path to get your current route name & conditionally add css to your menu.

<template>
 <NuxtLink to="/tous-les-articles" 
   :class="$route.path.toLowerCase().includes('tous-les-articles')
              ? 'active'
              : ''
          ">
  Nuxt website
 </NuxtLink>
</template>

Other way is available to show active link to your project navbar. For details you can have a look at this doc & play on sandbox: https://nuxtjs.org/examples/routing/active-link-classes/

Related