The active class in the Vue.js component navigation only takes effect after the second click

Within a menu component placed inside a view accessed through its own route (/how-it-works), I am facing an issue with the header component structure, outlined below:

<nav class="nav">
    <ul class="top-menu">
        <li v-for="menu in menuItems" v-bind:key="menu.id" v-bind:class="{'active' : menu.active}" v-on:click="setActiveMenu(menu)">
            <router-link :to="menu.url">{{ menu.name }}</router-link>
        </li>
    </ul>
    <div class="get-started">
        <router-link to="/">Get Started</router-link>
    </div>
</nav>

Upon visiting the route, it's noticed that even though menu.active is true, the corresponding active class doesn't get applied. However, when already within the /how-it-works route, the functionality works as expected, but only within that specific route. it appears to be a navigation issue between routes. The setActiveMenu function is structured as follows:

setActiveMenu: function(menu) {
    for (let i = 0; i < this.menuItems.length; i++) {
        this.menuItems[i].active = false;
    }
    menu.active = true;
}

Additionally, the menu array content is as follows:

menuItems: [
    {
        name: 'How It Works',
        url: '/how-it-works',
        id: 1,
        active: false
    },
    {
        name: 'Page 2',
        url: '/',
        id: 2,
        active: false
    },
    {
        name: 'Page 3',
        url: '/',
        id: 3,
        active: false
    },
    {
        name: 'Page 4',
        url: '/',
        id: 4,
        active: false
    },
    {
        name: 'Page 5',
        url: '/',
        id: 5,
        active: false
    },
    {
        name: 'Page 6',
        url: '/',
        id: 6,
        active: false
    }
]

The potential issue seems to lie in the treatment of the active state during component creation or when navigating between routes. How can I correctly manipulate the header in this scenario?

Answer №1

Just had a breakthrough.. instead of using a click event, I utilized the created method provided by vue.js:

created() {
    for (let i = 0; i < this.menuItems.length; i++) {
        this.menuItems[i].active = false;
        if (this.menuItems[i].url === this.$router.currentRoute.path) {
            this.menuItems[i].active = true;
        }
    }
}

I'm questioning if there's a better approach for achieving this?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the ideal way to utilize Vue within the framework of multiple pages?

When using the default Vue CLI setup, Vue is loaded from the index.html page. To work with Vue and dynamic content on the page, everything is typically handled in the App.vue file. But what if you want to make significant layout changes to the page? How d ...

Bootstrap 4 - DropDown option - Element is positioned above the navigation bar

Currently facing an issue with the DropDown menu. Whenever I add padding to the DropDown menu (class - drop_link), it ends up pushing the entire element over the <nav>. I'm unsure of how to prevent this from occurring. I attempted to disable som ...

How can I ensure my game or website fits perfectly on the screen without any need

I have recently developed a fun Erase-A-Man game that is optimized for mobile devices. However, I am facing an issue where users need to scroll to view all the letters on their screens. My goal is to make the game fit perfectly on all phone screen sizes so ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...

Execute a bash script from a local URL using fetch

I'm curious about converting a curl command into a bash script with input variables using fetch. It works perfectly in the console: curl -s http://localhost:3001/ident.sh | bash /dev/stdin x627306090abab3a6e1400e9345bc60c78a8bef57 2 10194897676576 ...

Three.js - Attempting to apply a texture to a plane consistently results in a black rendering

I'm having trouble applying a texture to a plane. The image I'm using is 256x256, but it's rendering black instead of showing the texture. Can anyone point out where I might be making a mistake? //set up the floor var floorTexture = new TH ...

Nested ng-repeat for dynamic variable rendering

I am facing an issue where I have a nested ng-repeat directive. I am attempting to create a dynamic second ng-repeat, using a key from the first one, but the current syntax is not working. Is there a different way to achieve this? Perhaps a different nota ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

The value being passed to the Child Component is only updating once

Within my Vue app, the parent component contains a list of months structured as shown below: https://i.stack.imgur.com/B9XQK.png Upon clicking on any month from the list, I aim to transfer its corresponding id to the child component named timeComponent. ...

How can I ensure the button remains disabled until all inputs are completed in Redux form?

I am currently studying a react-redux form example that you can find at the following link: In this example, the submit button is enabled if the user fills in at least one input field. I am curious to know if there is a way to enable the button only when ...

A guide on sending a post request with Axios to a parameterized route in Express

Recently, I set up an express route router.post('/:make&:model&:year', function (req, res) {   const newCar = {     make: req.params.make,     model: req.params.model,     year: req.params.year   }   Car.create(newCar);   res ...

Sorting information by class titles in AngularJS

Working with angularjs, take a look at my view code : <div style="width:70px;"> Show Online <input type="checkbox" ng-model="showonline" /> </div> <div ng-repeat="user in use ...

Is there a way to modify my function expression without using any state variables?

Currently working on a jQuery game where the player is generated upon clicking a button. Below is the function expression I'm using to store the player's information: var getPlayerData = function() { return { name: $("#name").val(),/ ...

How can a JavaScript code be used to navigate to a different HTML file within the same directory that is stored within a folder?

Here is the sample HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewpor ...

Issue with Google Script not initializing in a second form

I'm currently working on a project that is bound to a Google Sheet container. The purpose of this project is to search for a specific value in one column, and based on the result, either mark the record as complete, allow for missing values to be fill ...

Display various child components in a React application depending on the current state

I'm currently developing a brief React quiz where each question is represented as an independent component. I aim to swap out the current question component with the next one once a question is answered. Here's the present state of my root compon ...

Steps to duplicate a Vuex store and incorporate it into a fresh store

In my endeavor to create a method in Electron that allows for the duplication of Vuex commits from one Window to another using IPC, I aim to simplify developers' usage of the Vuex store across different browser windows without the need for manual IPC ...

Transitioning from using lerna to adopting pnpm

We are in the process of transitioning our project from Lerna to PNPM and we currently have a script that we run. Here are the commands: "postinstall": "npm run bootstrap" "bootstrap": "lerna bootstrap --hoist", &quo ...

Struggling to pass data changes between child components in Vuejs2?

Encountering a challenge with my current project. I have implemented a vuejs2 parent-child structure as outlined below Parent app child product-list product product-image colour-select In the product template, I initialize the sibling components ...

How to dynamically change the class of an element that contains other elements using JavaScript and JQuery

I have created a blog archive with the following format: +Year +Month Title Here is a snippet of the code: <ul> <span class="toggle">+</span> <li class="year">$year <ul> <span ...