A guide on applying a class to the parent element in VUEjs upon clicking the child menu

How can I dynamically add an active class to the <a> element of a sibling <router-link> when clicking on the sub menu in the provided template?

<ul class="depth1">
  <li class="m1">
    <router-link to="/introduce/Introduce" @click="selected = 1" :class="{ active: selected == 1 }"><span>menu1</span></router-link>
    <ul class="depth2 sm1">
      <li><router-link to="" @click="selected = 1">sub menu</router-link></li> 
      <li><router-link to="" @click="selected = 1">sub menu</router-link></li> 
      <li><router-link to="" @click="selected = 1">sub menu</router-link></li> 
    </ul>
  </li> 
   <li class="m2">
    <router-link to="/introduce/Introduce"  @click="selected = 2" :class="{ active: selected == 2 }"><span>menu2</span></router-link>
    <ul class="depth2 sm1">
      <li><router-link to="" @click="selected = 2">sub menu</router-link></li> 
      <li><router-link to="" @click="selected = 2">sub menu</router-link></li> 
      <li><router-link to="" @click="selected = 2">sub menu</router-link></li> 
    </ul>
  </li> 
</ul>

<script>
export default {
  data: function () {
    return {
      selected: false, 
    };
  },
  methods: { 
  },
};
</script>

Answer №1

Your approach is almost there, but the issue with the click handler arises from incorrect implementation.

In order to attach a click event to the main element of the <router-link> (specifically, the <a> tag), utilize @click.native:

<router-link to="" @click.native="activateMenu">submenu</router-link>
                         ^^^^^^^

Answer №2

However, why not take advantage of the default behaviors provided by vue-router, such as automatically applying an active class to links when the target route is active? The demo below illustrates this point:

const Home = {
  template: '<div><h2>Home</h2></div>'
}
const About = {
  template: '<div><h2>About</h2></div>'
}

const Users = {
  template: `
    <div>
      <h2>Users</h2>
      <router-view></router-view>
    </div>
  `
}

const User = {
  template: '<div>{{ $route.params.username }}</div>'
}

const router = new VueRouter({
  mode: 'history',
  routes: [{
      path: '/',
      component: Home
    },
    {
      path: '/about',
      component: About
    },
    {
      path: '/users',
      component: Users,
      children: [{
        path: ':username',
        name: 'user',
        component: User
      }]
    }
  ]
})

new Vue({
  router,
}).$mount('#app')
a.router-link-active {
  color: #f66;
}

li.router-link-active a {
  color: #f66;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Active Links</h1>
  <ul>
    <li>
      <router-link to="/">/</router-link>
    </li>
    <li>
      <router-link to="/" exact>/ (exact match)</router-link>
    </li>

    <li>
      <router-link to="/users">/users</router-link>
    </li>
    <li>
      <router-link to="/users" exact>/users (exact match)</router-link>
    </li>

    <li>
      <router-link to="/users/evan">/users/evan</router-link>
    </li>
    <li>
      <router-link to="/users/evan#foo">/users/evan#foo</router-link>
    </li>
    <li>
      <router-link :to="{ path: '/users/evan', query: { foo: 'bar' }}">
        /users/evan?foo=bar
      </router-link>
    </li>
    <li>
      <!-- #635 -->
      <router-link :to="{ name: 'user', params: { username: 'evan' }, query: { foo: 'bar' }}" exact>
        /users/evan?foo=bar (named view + exact match)
      </router-link>
    </li>
    <li>
      <router-link :to="{ path: '/users/evan', query: { foo: 'bar', baz: 'qux' }}">
        /users/evan?foo=bar&baz=qux
      </router-link>
    </li>

    <li>
      <router-link to="/about">/about</router-link>
    </li>

    <router-link tag="li" to="/about">
      <a>/about (active class on outer element)</a>
    </router-link>
  </ul>
  <router-view class="view"></router-view>
</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

"Navigate to the URL of the image using the window location

Struggling to incorporate a share button for an image, the current javascript configuration is as follows: url: window.location.href The goal is to make the url point directly to the image instead of the entire webpage. Check out the revised config below ...

Bringing in an external .js file into nuxt.config.js

Having trouble importing config.js with the project's API keys and getting undefined as a return value. //config.js var config = { fbAPI: "key" } - //nuxt.config.js const cfg = require('./config') env: { fbAPI: cfg.apiKey } Wonder ...

Why does the React input value keep its value when the modal is re-rendered, despite the state being updated correctly?

Take a look at this sandbox link for the code snippet: Sandbox Showcased below is a table structure: https://i.sstatic.net/3F3Mc.png By clicking on the 'edit' button, a modal window opens up as shown below allowing you to edit input fields (onC ...

Unveil Secret Divs with a Click

I am in search of a way to display a hidden div when I click on a specific div, similar to the expanding images feature in Google's image search results. I have made progress with my limited knowledge of javascript, as shown in this CodePen: http://co ...

Tracing back the tainted canvas glitch in MDN's demonstration and resolving it

I am currently working my way through the Canvas tutorial on MDN. Everything was going smoothly until I reached the Pixel manipulation, specifically a color picker example. However, when using getImageData, I encountered this error: MDNTutorialBaseppp ...

Issue with React select dropdown not properly updating selected value

My website has a form with the default value of ethExperienceLevel set to "BEGINNER". I have a function that is supposed to update the selected state when switching between options in a dropdown list, triggered by an onChange handler. However, I noticed ...

Testing Tools for AJAX Integration

Searching for AJAX testing resources. Are there any no-cost tools out there for conducting AJAX tests? Edit 2: Besides Firebug, are there any other tools available? ;) ...

Locate the nested route within one of the child components in React Router that corresponds to a specific id

Picture this scenario where I have a list of routes: const routes = [{ id: "1", path: "animals", children: [{ id: "1.1", path: "birds", children: [{ id: "1.1.1", path: "co ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Designing a professional networking platform with a feature that allows users to preview their posts before publishing,

Is there anyone who can provide insights on how to integrate a "Post Form" functionality similar to that of LinkedIn, focusing on the behavior rather than the exact user interface? Does it involve using a rich text editor? If so, could you suggest a packag ...

`Why my React function calls are not being tested properly with Jest and Sinon?`

I need help determining how many times my React class method is executed after an event. I've experimented with sinon.spy and jest.fn() but haven't had success. Attempt using sinon.spy: test('Example test', (done) => { const page ...

How can I use JavaScript to set a background image for a div?

My goal is to create a hover effect on a div that changes the background image and text color simultaneously. I've managed to change the text color successfully, but the background image isn't cooperating. Here's the code I'm using: In ...

What is the best way to retrieve values from a multi-dimensional array?

I am working with Angular and have an array named testUsers that contains sample data as shown below: this.testUsers = [ {email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94a5d4f2f5fff1baf7fbf9">[email pr ...

Dealing with function scoping problems and transitioning to Arrow Functions

Currently, I am delving into the world of arrow functions and attempted to convert my code snippet below. Unfortunately, I have encountered a scope issue with funcCall and enterKey. My intuition tells me that utilizing an arrow function could potentially ...

Creating a Server-Side Rendered application from scratch

Currently, we are in the process of developing a Nuxt application using npm run generate and deploying it as a Static Site Generator (SSG). However, an issue has arisen where the application is being built as a Client-Side Rendered (CSR) app instead of Ser ...

What is the best way to retrieve the row IDs in react-table?

Using table-v7 and attempting to implement a delete modal, but unsure of how to retrieve the ids of my rows and set them in my axios request The function is located in a hook file, and if I use row.original._id, I can obtain the id but it only works withi ...

The most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...

Troubleshooting the lack of communication between multiple Subscribers in RxJS/Angular when sharing one observable

For a project using Angular 4, I am implementing an HTTP call to retrieve data from the backend. To optimize performance, I cache the data once it is fetched so that subsequent requests do not require additional API calls. getApplication(): Observable< ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

Obtaining the final href/link without the need to click on it in a javascript call using Selenium

Currently web scraping a lengthy table of HTML links (permitted under Terms of Service). However, all the links are JavaScript calls (href="javascript:;"), so using get_attribute() to retrieve the link will not be effective. I am trying to avoid actually c ...