Managing the transition of the object in question

I am in the process of designing a navigation bar. I have created an array to store the information of the tabs present in the nav bar.

            tabs: [
                { name: 'All',id: "dash.courses.all", to: 'all', current: false },
                { name: 'Self-paced Learning',id: "dash.courses.oneToOneClasses", to: 'selfPacedLearningComp', current: false },
                { name: '30 Days Challenge',id: "dash.courses.selfPacedLearningComp", to: 'thirtyDaysChallenge', current: false },
                { name: 'Group Classes',id: "dash.courses.groupClasses", to: 'groupClasses', current: false },
                { name: '1-to-1 Classes',to: "dash.courses.thirtyDaysChallenge", to: 'oneToOneClasses', current: false },
            ]

Whenever a new route is clicked, it updates the newly clicked tab by setting the current property to true.

How can I change the previous nav item to false? Currently, they all change to true one by one as they are clicked.

I believe if I store a value as previous

      setCurrent(tab)
      { 
          
          let newArr = this.tabs.map(obj => {
          if (obj.id === tab) {
            return {...obj, current: true};
          }

          return obj;
        })
        this.tabs = newArr
        console.log(newArr)
      }
    },

This is what i've got so far, it has to go around 3 routes ahead till the one before vanishes...

<script>
export default {
    components: {
    },
    data()
    {
        return {
            prevTab: null,
            tabs: [
                { name: 'All',id: "dash.courses.all", to: 'all', current: false },
                { name: 'Self-paced Learning',id: "dash.courses.oneToOneClasses", to: 'selfPacedLearningComp', current: false },
                { name: '30 Days Challenge',id: "dash.courses.selfPacedLearningComp", to: 'thirtyDaysChallenge', current: false },
                { name: 'Group Classes',id: "dash.courses.groupClasses", to: 'groupClasses', current: false },
                { name: '1-to-1 Classes',to: "dash.courses.thirtyDaysChallenge", to: 'oneToOneClasses', current: false },
            ]
        }
    },
    methods: {
      setCurrent(tab)
      { 
          this.prevTab = this.$route.name
          let newArr = this.tabs.map(obj => {
          if (obj.id === tab) {
            return {...obj, current: true};
          }
          if(obj.id === this.prevTab) {
            return {...obj, current: false}
          }

          return obj;
        })
        console.log('previous ',this.prevTab)
        console.log('route name', this.$route.name)
        this.tabs = newArr
      }
    },
    mounted()
    {
      this.prevTab = this.$route.name
      const newArr = this.tabs.map(obj => {
        if (obj.id === this.$route.name) {
          return {...obj, current: true};
        }

        return obj;
      });
      this.tabs = newArr
    }
}

Answer №1

Add a watcher to monitor changes in the route name

watch: {
    "$route.name": {
      handler(routeName) {
        this.tabs.forEach((tab) => (tab.current = routeName === tab.name));
      },
      // ensuring immediate callback execution
      immediate: true,
    },
  }

Typically, utilizing the watcher routeName value above should suffice to trigger any desired side effects, but if keeping track of current on each tab is absolutely necessary, the provided code will achieve the intended result.

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

Is it possible to capture "global" events while handling nested iframes?

My dilemma involves capturing a keypress event, but the user can potentially be navigating through multiple layers of iframes nested within each other. Initially, I attempted to add the event listener to the document, only to realize that it wouldn't ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

What steps can be taken to create a seamless navigation experience that effectively emphasizes the user's current location?

Is there a way to dynamically add the "current" class to the navigation menu based on the user's current location on the page? This would make it easier for users to see which section of the site they are viewing as they scroll through. Check out this ...

Having trouble accessing the card number, expiration date, and CVC in vue using Stripe

Although I am aware that Stripe securely stores all information and there is no need for me to store it on my end, I have a specific requirement. When a user begins typing in the input area, I want to capture and access the card number, expiry date, and ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

Mastering linear regression calculations using vue.js and chart.js

Take for instance, with the current dataset, I am looking to showcase a linear regression I managed to do this in Vista and now I need guidance on how to proceed with the calculation. I am not too familiar with using the formula Here is my HTML: <canva ...

Can REST calls be initiated when the CSP is unable to be modified from the default-src: 'none'?

Sometimes, I wonder if this question is silly because it goes against the purpose of the Content Security Policy. There's a webpage located at foo.baz.com that requires data from bar.baz.com to function locally. Below is the code snippet for the func ...

Access the value retrieved from a form on the previous page using PHP

I'm struggling with extracting values from radio buttons on a previous page. Currently, my HTML and PHP code works fine with the search bar, which is the first form below. However, I'd like to add radio button filters below the search bar. <s ...

How to fetch React route parameters on the server-side aspect

I encountered a challenge while working with ReactJS and ExpressJS. The user uploads some information on the /info route using React and axios. Then, the user receives route parameters from the server side to redirect to: axios.post('/info', Som ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Is it better to conceal modals or completely eliminate them from the DOM when working with React?

I am currently developing a React application that involves multiple modals, with only one active at a time and no nested modals. I am torn between two approaches for handling the showing and hiding of these modals: The first approach involves having a b ...

Create a nested array of subcategories within an array object

Currently, I am working on integrating Django Rest and Angular. The JSON array received from the server includes category and subcategory values. My goal is to organize the data such that each category has its related subcategories stored as an array withi ...

I need the sidebar to be visible across all interfaces

https://i.stack.imgur.com/iEgAF.png I have developed a website for employee monitoring with six interfaces. The first interface is for sign-up, the second for logging in, the third for creating projects, the fourth for displaying projects, the fifth for c ...

Removing a faded out div with Vanilla JavaScript

I am struggling with a JS transition issue. My goal is to have the div automatically removed once it reaches opacity 0. However, currently I need to move my mouse out of the div area for it to be removed. This is because of a mouseleave event listener that ...

display the text from the template after selecting it (including both the text-field and value-field)

I'm currently utilizing BootstrapVue. In my b-form-select component, I display the name (as the text field) in the selection within my child.vue and emit the age (as the value field) to my parent.vue. This functionality is functioning as intended. H ...

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...

Determination of an arc trajectory using JavaScript

I have been trying to figure out how to replicate this effect. The Red arrowhead remains stationary while the background features a curved path. Currently, I am adjusting the background position to give the illusion of the arrowhead moving along the curved ...

Navigating with Vue Router and waiting for a certain amount

I am currently working on a Vue 3-pages application that utilizes VueRouter. One issue I am encountering is that on the first page, I have a timer set up to make a server request every minute using setTimeout. However, when moving to the next page, the t ...