The method for triggering an event upon mounting in Vuejs

I have a sidebar displayed below:

<template>
        <section>
            <div class="sidebar">
                <router-link v-for="(element, index) in sidebar" :key="index" :to="{ name: routes[index] }" :class='{active : (index==currentIndex)  }'>{{ element }}</router-link>
            </div>

            <div class="sidebar-content">
                    <div v-if="currentIndex === 0">
                        Profile
                    </div>
                    <div v-if="currentIndex === 1">
                        My Tickets
                    </div>
            </div>
        </section>
</template>
<script>

    export default {
        mounted() {
            EventBus.$on(GENERAL_APP_CONSTANTS.Events.CheckAuthentication, () => {
                this.authenticated = authHelper.validAuthentication();
            });
            
            this.checkRouter();
        },
        data(){
            return {
                currentIndex:0,
                isActive: false,
                sidebar: ["Profile", "My Tickets"],
                routes: ["profile", "my-tickets"],
                authenticated: authHelper.validAuthentication(),
            }
        },
        computed: {
            getUser() {
                return this.$store.state.user;
            },
        },
        methods: {
            changeSidebar(index) {
                this.object = this.sidebar[index].products;
                this.currentIndex=index;
            },
            checkRouter() {
                let router = this.$router.currentRoute.name;
                
                if(router == 'profile') {
                    this.currentIndex = 0;
                } else if(router == 'my-tickets') {
                    this.currentIndex = 1;
                }
            },
        },
    }
</script>

When a link is clicked in the sidebar, the route changes to either 'http://.../my-account/profile' or 'http://.../my-account/my-tickets'. However, the issue arises as the currentIndex variable does not update accordingly, causing the content and active class in the links not to change. How can I adjust the currentIndex based on the routes? Is there a Vue-specific way to achieve this through an event trigger? Your guidance on resolving this issue would be greatly appreciated.

Answer №1

It seems like you're looking to dynamically set the value of currentIndex based on the currently active route. One approach could be creating it as a computed property:

currentIndex: function(){
    let currentRoute = this.$router.currentRoute.name;
    
    if(currentRoute == 'profile') {
        return 0;
    } else if(currentRoute == 'my-tickets') {
        return 1;
    }
}

You can make better use of Vue's reactivity by eliminating duplicate elements and making properties reactive.

<div class="sidebar-content">
    {{ sidebar[currentIndex] }}
</div>

Consider making object a computed property for efficiency, similar to:

computed: {
    getUser() {
        return this.$store.state.user;
    },
    object() {
        return this.sidebar[this.currentIndex].products;
    }
},

Answer №2

To access information about the current route in a Vue component template, simply use this.$route. For more details, you can refer to the documentation. You don't have to create custom logic like checkRouter() currentIndex. Here is a simple example:

<div class="sidebar-content">
     <div v-if="$route.name === 'profile'">
          Profile
      </div>
      <div v-if="$route.name === 'my-tickets'">
          My Tickets
       </div>
     </div>

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

Vue.js is encountering an issue with NeDB where it is unable to locate the database files

Creating a Vue project: vue init webpack-simple nedbtest Installing the Nedb database: npm i nedb -S Modifying App.vue : <template> <div> <button @click="insert">Insert Data</button> <button @click="find">Find D ...

Closing a Vue modal with a button

Utilizing the bootstrap-vue framework for my modal, I encountered an issue. Upon clicking the button labeled OPEN MODAL, the modal opens with footer buttons OK and CANCEL, which work as expected to close the modal as per bootstrap-vue's default behavi ...

Why doesn't Vue's computed method call the 'get' function after setting a dependent value in the 'set' function

Allow me to explain how I define a computed value: Template : <date-picker v-model="rangeDate" type="date" format="jYYYY/jMM/jDD" display-format="jYYYY/jMM/jDD" input-c ...

Unveiling the power of Axios and Vue in fetching API data: The quest for

I've encountered a problem while trying to integrate my API with Vue/Axios. The issue arises when I attempt to store the data retrieved by Axios into an empty variable within the data object of my component. It throws an "undefined at eval" error. Can ...

Guide on using axios in vue.js to interact with the API

I need help with a functionality on my website where users can select a car brand from a list of radio buttons. After selecting a brand, I want to retrieve an array of models from the server and display them on a new page. Can someone guide me on what spec ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...

Leveraging Axios in the nuxtServerInit function

I am facing an issue where I need to fetch remote data and display it on multiple pages. The network call is being made in the store/index.js file: export const state = () => ({ contact: { hello: "World" } }); export const actions = { async ...

Setting a default date dynamically for v-date-picker in the parent component, and then retrieving the updated date from the child component

I'm working with a custom component that utilizes the v-date-picker in various instances. My goal is to have the ability to dynamically set the initial date from the parent component, while also allowing the date to be modified from the child componen ...

Tips for making axios unique with @nuxtjs/auth-nextTips for modifying axios with @

I've been grappling with this issue for the past three days without any luck in finding a solution. My Nuxt.js frontend relies on the auth module to acquire a JWT token from a DRF backend. Upon logging in, the server returns the following message: Fo ...

Using a .vue file in an HTML document: A step-by-step guide

After creating a hello.vue file, I am unsure how to actually use it in an HTML file. I have already set up webpack, <template> <p>Hello</p> <p>{{message}}</p> </template> <script> module.exports = { data: ...

The dynamic trio of Laravel, inertiajs, and vuejs

I am currently working on a project that involves laravel, inertiajs, and vuejs. Whenever I attempt to delete a user from the database, I consistently encounter a 404 | NOT FOUND error. My goal is to successfully delete the user by clicking a button using ...

Placing a component within a div element using Vue

I recently integrated a Vue module to make objects draggable and resizable on my project. In my design, I envisioned creating movable and sizable boxes that contain dropdown menus, input fields, and radio buttons. As a starting point, I have included a sim ...

Why is TinyMCE removing my custom MPDF HTML elements?

I have a Vue application with a Symfony backend. I am using TinyMCE to edit documents that are generated by mpdf. In the mpdf twig content, I need to add a page footer on certain pages and exclude it on others. To achieve this, I have created custom HTML t ...

Issues encountered with vue element checkbox functionality while in edit mode

I am currently utilizing checkboxes provided by Vue Element. You can take a look at them here: . However, I am encountering an issue where users are unable to select checkboxes in edit mode. Any assistance would be greatly appreciated. <el-checkbox-g ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

Error in vue.js: Cannot access property '$forContext' of null object

I have come across a peculiar issue. Despite everything appearing to function correctly, when I submit inputs (whether using the form submit event with a <form/> element or the keyop.enter event), I encounter the following error in my JS console that ...

A helpful guide on incorporating data from one component into another component in Vue.js

Recently, I started working with Vue and I am facing a challenge in transferring an array from one component to another. The first component contains the following data that I need to pass on to the second component: const myArray = []; Both components a ...

Encountering a "Cannot read property 'protocol' of undefined" error when attempting to implement a search bar with Laravel and Vue JS using the Vuetify Framework

Currently, I am working on creating a search bar using Laravel and Vue JS with the Vuetify framework. Below are my controller functions: /** * Retrieve names and references of all projects for the user. * * @param \Illuminate\Http\Reques ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...