-1

I have a template like this :

<div id="vue-instance">
  <ul>
    <li v-for="item in inventory" v-on:click="say()" v-bind:class="{active:isActive}" > {{ item.name }} - ${{ item.price }}
    </li>
  </ul>
</div>

And from my "controller" :

var vm = new Vue({
 el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', price: 1000},
      {name: 'MacBook Pro', price: 1800},
      {name: 'Lenovo W530', price: 1400},
      {name: 'Acer Aspire One', price: 300}
   ],
    isActive : false
 },
  methods: {
    say: function () {
      this.isActive = !this.isActive 
    }
 }

});

With this when i click one item from the list, all items are affected to active class. My question is how to toggle individual element?

Thank you.

2

2 Answers 2

2

You need a active flag on each item to be able to track them individually.

For example:

{name: 'MacBook Air', price: 1000, isActive: false},
{name: 'MacBook Pro', price: 1800, isActive: true}

You will then will be able to bind the class and click event to item.isActive by doing something like this:

<li v-for="item in inventory" v-on:click="item.isActive = !item.isActive" v-bind:class="{active:item.isActive}" > {{ item.name }} - ${{ item.price }}
</li>
Sign up to request clarification or add additional context in comments.

Comments

0

Notice that if class name contains dash "-" vue can't comile the template. I tried with class with this name "main-container" and face this issue.

Comments

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.