Victor
Victor

Reputation: 714

Target clicked element in Vue

In Vue.js how do you target/detect the clicked element to perform a basic toggle class?

I've written this which toggles successfully but when you click an a the class is applied to to all li's

HTML

  <ul id="app" class="projects">
    <li v-bind:class="dyClass"><a href="" v-on:click.prevent.stop="show = !show">Project A</a></li>
    <li v-bind:class="dyClass"><a href="" v-on:click.prevent.stop="show = !show">Project B</a></li>
    <li v-bind:class="dyClass"><a href="" v-on:click.prevent.stop="show = !show">Project C</a></li>
    <li v-bind:class="dyClass"><a href="" v-on:click.prevent.stop="show = !show">Project D</a></li>   </ul>

JS

  new Vue({
    el: '#app',
    data: {
      show: false,
    },
    computed: {
      dyClass: function() {
        return {
          show: this.show
        }
      }
    }
  })

I'm new to Vue.

EDIT.

I managed to get it working with a mix of help from below, but I dont seem to be able to get the toggle effect.

  <ul id="app" class="projects">
    <li :class="{show:selected == 1}">
      <a href="" @click.prevent.stop="selected = 1" >Exposure</a>
    </li>
    <li :class="{show:selected == 2}">
      <a href="" @click.prevent.stop="selected = 2" >Exposure</a>
    </li>
    <li :class="{show:selected == 3}">
      <a href="" @click.prevent.stop="selected = 3" >Exposure</a>
    </li>        
  </ul>

and

  new Vue({
    el: '#app',
    data: {
      selected: false,
    }
  });

Upvotes: 2

Views: 20487

Answers (2)

Roland
Roland

Reputation: 27719

As i understand you have some li items and you want to add an active class when a specific li gets clicked.

Solution:

the "html" part:

<div id="app">
  <ul class="projects">
    <li v-for="project in projects"
        :key="project.id"
        :class="{ active: project.id === activeProjectId }"
        @click="activeProjectId = project.id"
    >
      <a href="#">{{ project.name }}</a>
    </li>
  </ul>
</div>

The "vue" part

new Vue({
  el: "#app",
  data: {
        projects: [
     { id: 1, name: 'Project A' },
     { id: 2, name: 'Project B' },
     { id: 3, name: 'Project C' },
     { id: 4, name: 'Project D' },
    ],
    activeProjectId: 1
  },

})

Then add some css to the 'active' class.

For more, See the fiddle

Upvotes: 3

user7289982
user7289982

Reputation:

You can pass element to function ($event):

:click=dyClass($event) Then in computed:

dyClass: function(event) {
    event.target.toggleClass('whatever')
}

Upvotes: 7

Related Questions