1

I'm dinamically building a list of items using v-for.

<html>
<head>
  <meta charset="utf-8">
</head>

<body>
  <div id="main">
    <div id="vue-wrapper">
      <div v-for="item in all_items">
        <div class="single-item" v-on:click="selectItem(item)"></div>
        </div>
      </div>
    </div>
  </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js">
</script>
</html>

vue.js file

var vue = new Vue({
  el: '#vue-wrapper',
  data: {
    all-items: [{ name: 'Jhon', surname: 'Red' }, { name: 'Rick', surname: 'White' }]
  },
  methods: {
    selectItem: function (item) {
      if($(this).hasClass('active')){
        console.log(item.name);
      } else {
        $(this).addClass('active');
      }
  }
});

When the single-item is clicked i need to print item.name if the div has class 'active', or just add it otherwise. Problem is that if($(this).hasClass('active')) always return false even if the class is set to active. I've tried to use also $(this.$el) instead of $(this) without success. I tried also to use a Jquery click handler but i don't know how to obtain item.

Razinar
  • 727
  • 3
  • 13
  • 21
  • 4
    If you're using code like `$(this).hasClass` in a Vue app you've misunderstood the point of Vue. – ceejayoz Nov 20 '17 at 20:13
  • 2
    To elaborate a bit, your `data` array should have something along the lines of `all-items: [{ name: 'Jhon', surname: 'Red', active: true }`. Vue's about reacting to the data - you should be detecting/changing active state in the data - `this.all-items[0].active = true` sort of stuff, not via classes in the DOM. Then, apply classes in the template [based on the Vue data](https://vuejs.org/v2/guide/class-and-style.html). – ceejayoz Nov 20 '17 at 20:17
  • `v-bind:class="{ active: item.isActive }" v-on:click="item.isActive=!item.isActive"` – Юра Панарин Nov 20 '17 at 20:27
  • I think that leaving this question open would allow to give an answer that in my opinion is not answered in the linked questions – Giorgio Tempesta Mar 10 '21 at 09:22

0 Answers0