0

I'm trying to toggle between the 2 images by triggering a function on click event, as shown below, how do I apply the same idea to different list items to toggle the images individually for each item? right now, all the list items same image because of one global value i.e val

var app = new Vue({
  el: '#app',
  data: function() {
    return {
      val:true,
        selectedImg:"",
        checked: "@/assets/images/check.png",
        unchecked: "@/assets/images/uncheck.png",
        items: [
           { message: 'laundry' },
           { message: 'cooking' },
           { message: 'cleaning'}
          ]
    }
  },

  methods: {
   myfunc () {
          this.val = (this.val === true ? false : true) 
           
          if(this.val === true) {
            this.selectedImg = this.checked
          }  else  {
            this.selectedImg = this.unchecked
          }
      },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
   <ul>
     <li v-for="item in items" :key="item.message">
       <button @click="myfunc"><img :src="selectedImg"/></button>
         {{ item.message }}  
     </li>
   </ul>
   
</div>

1 Answer 1

1

You should move selectedImg and val into items objects and pass item to myfunc function. You can also look at the answer in codepen.

var app = new Vue({
  el: '#app',
  data: function() {
    return {
        checked: "@/assets/images/check.png",
        unchecked: "@/assets/images/uncheck.png",
        items: [
           { message: 'laundry', selectedImg:"" , val:true},
           { message: 'cooking', selectedImg:"", val:true},
           { message: 'cleaning', selectedImg:"", val:true}
          ]
    }
  },

  methods: {
   myfunc (item) {
          item.val = (item.val === true ? false : true) 
           
          if(item.val === true) {
            item.selectedImg = this.checked
          }  else  {
            item.selectedImg = this.unchecked
          }
      },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
   <ul>
     <li v-for="item in items" :key="item.message">
       <button @click="myfunc(item)"><img :src="item.selectedImg"/></button>
         {{ item.message }}  
     </li>
   </ul>
   
</div>

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

1 Comment

Or you can even extract the logic to a new component of a custom checkbox :)

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.