SwadhIn
SwadhIn

Reputation: 747

How to remove particular class name from an selected element in VueJs?

This is what my vuejs methods looks like. Here in the changeRoute function I can change class name by e.target.className = 'clicked'; But when I try to remove that class name from other elements I cant do it by pre.removeClass('clicked'); How can I accomplish this ?

<script>   
export default {

  components: { 
      
  },
  data() { 
      return {

      }
  },
  methods: {
      changeRoute(e, route) {
           
        var pre = this.$el.querySelector('.clicked');
        if(pre) {
            // pre.removeClass('clicked'); 
        }

        this.$router.push({
            name: route
        }); 
        e.target.className = 'clicked';
          
      }
  },
  mounted() {
      this.$nextTick(() => {
 
      })
  }
}

</script>

Also how can push class name rather than replace all by e.target.className = 'clicked';

Upvotes: 2

Views: 11291

Answers (3)

E. Hekkert
E. Hekkert

Reputation: 137

Use actual Vue to accomplish this task. I could explain here how but the Vue page does it quite well.

https://v2.vuejs.org/v2/guide/class-and-style.html

Upvotes: 1

veritas
veritas

Reputation: 432

If the selected element is part of a li list and class should be added (and consequently removed from previous clicked li), here's a good solution by Herteby on the VueJS Forum

https://forum.vuejs.org/t/how-to-add-active-class-to-element/28108/2

Upvotes: 1

Oli Crt
Oli Crt

Reputation: 1173

You can use classList.add and classList.remove for this.
But it seems like you want to style link depending on the current route which can be done with vue-router as it adds class on the links matching the current route.
Vue-router active class

Upvotes: 2

Related Questions