0

I am having trouble adding an active class when clicking a link.

I have the dynamic class setup with a click listener that passes an argument to the function but the class does not update. I am not sure why. The 'Dashboard' link is red when page is refreshed so I know it is working to an extent.

<template>
  <b-list-group>
    <b-list-group-item
      v-for="(link, index) in menu"
      :key="index"
      :href="link.sectionId"
      :class="{active: link.title === selectedLink}"
      :click="isActive(link.title)"
    >
      {{link.title}}
    </b-list-group-item>
  </b-list-group>
</template>

<script>

export default {
  data() {
    return {
      selectedLink: 'Dashboard',
      menu: [
        {
          title: 'Dashboard',
          icon: labStuffs,
          sectionId: '#'
        },
        {
          title: 'Lactose intolerance',
          icon: labStuffs,
          sectionId: '#'
        }
      ]
    }
  },
  methods: {
    isActive(title) {
      this.selectedLink === title
    }
  }
}
</script>

<style scoped lang="scss">
.active {
  background-color: red;
}
</style>

Expecting the background colour of clicked link to change. Only the dashboard link is red and whenever I click anything else, nothing happens.

4
  • Shouldn't this.selectedLink === title in your method be this.selectedLink = title instead? Commented Jun 19, 2019 at 13:39
  • I get a console warning saying there is an infinite loop Commented Jun 19, 2019 at 13:41
  • Oh, you have both an href and a click event on the b-list-group-item which renders as an anchor tag in the html. Might want to handle route change and active class in the same logic? Also, shoudn't it be @click instead of :click Commented Jun 19, 2019 at 13:45
  • Nice idea @BrandonFranklin however even without the href it is still not changing the background colour. Commented Jun 19, 2019 at 13:52

1 Answer 1

1

Here is a working example of your code.

I changed the :click to @click and the following.

methods: {
    isActive(title) {
      this.selectedLink = title // Had === before
    }
  }

https://codesandbox.io/s/vue-template-y3k12?fontsize=14

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.