Methods for attaching values to individual list items in Vue to switch images

Is there a way to toggle between two images by triggering a function on click event for different list items? Currently, all the list items display the same image because of a global value. How can I modify the code to toggle the images individually for each item?


        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>

Answer №1

To improve your code, consider moving the variables selectedImg and val into items objects and pass the item to the myfunc function for better organization and functionality. For a clearer understanding, you can refer to the solution provided in this codepen link.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery Ajax to Send Values Between Functions and Replace Nulls

I need assistance with handling the value from a dropdownlist in my JavaScript function. The function works well if the value is not Null, but I want to replace a Null value with the static value "asc" before passing it to the next function. function g ...

using javascript to target a specific css selector attribute

I have a CSS file with the following code: .datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4; font-size: 16px ;font-weight: normal; } Is there a way to use JavaScript to dynamically change the font size? The code below worked ...

Automatically create CSS properties for left and top using absolute positioning

When looking at these websites as models: On each of them, I noticed that there is a well-organized column of boxes for every post. I attempted to recreate this using various methods, but couldn't achieve the exact layout on my own website. It seems ...

I'm looking to filter this array based on the value of a subarray that the user will specify the key and value for. How can I accomplish

Given the input var key="value_0" and var input="hello", I need to filter the array in TypeScript based on these values. The filtering criteria involve checking if the array elements contain a subarray with key="value_0" and if the value of this key includ ...

Retrieve an array of object values using Angular and TypeScript

I'm attempting to extract the values of objects in an array using a nested for loop. I am receiving JSON data as shown below and have written the following TypeScript code to achieve this. However, I am unable to successfully bind the values to the te ...

Show information from a form within a react webpage

I'm currently working on a to-do app and my directory structure includes the following main files: App (renders the main page with header and buttons) export default class App extends React.Component { constructor(props) { super(props); thi ...

Tips for posting a data-uri image on Pinterest

I'm attempting to post a data-uri image on Pinterest. Here is the code I am using: <a target="_blank" href="https://www.pinterest.com/pin/create/button/"> <img class="pin-image" src="data:image/png;base64,…"> </a> Following th ...

Delivering a static Angular app through an Express Server

In my current setup, I have an Angular app being served as static content in an Express Server. When Express serves static files, it automatically adds an ETag to them. Subsequent requests will then check if the ETag matches before sending the files agai ...

The presence of a Bootstrap addon is resulting in horizontal scrolling on mobile devices within the webpage

I am encountering a peculiar issue with an input-group in my cshtml file which features a Bootstrap addon. The problem arises on mobile devices, where upon focusing on the input field, the page scrolls horizontally to the right, revealing the right margin ...

Tips for choosing an <li> element with JavaScript

<style> .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; dis ...

Issue encountered while serializing the `.product` object retrieved from the `getStaticProps` function in NextJS, in conjunction with

I ran into an error message saying "Error: Error serializing .product returned from getStaticProps in "/products/[id]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value." This issue occurred while I was attempting to crea ...

Cloud function for Firestore to recursively update a subcollection or collection group

I've been working on this cloud function: import pLimit from "p-limit"; const syncNotificationsAvatar = async ( userId: string, change: Change<DocumentSnapshot> ) => { if (!change.before.get("published") || !change.after.exists) { ...

How to create a transparent background on a canvas

Looking for help with analyzing my HTML, CSS, and JavaScript (THREE.js) code to achieve the desired output mentioned in the title. //**MY HTML CODE** <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&qu ...

What is the best way to generate a fresh array by utilizing a specific search parameter?

I'm currently exploring ways to create a search box feature. Within my project, I have an array called passengersData that is being fetched from a Redux store. Most examples I've come across regarding search functionality in React involve utili ...

The view of the Google map is filled with numerous rounded tiles

Map divided into 3x3 tiles I am looking to customize the appearance of my map and remove all spaces and rounded corners to create a seamless, undivided visual. Is there a way to modify a map tile attribute to achieve this effect? Below is the code snippet ...

Error in SO Embed Snippet Fiddle due to Bootstrap 4 JS Issue

Just wondering, any idea why the bootstrap 4 js is throwing this error: https://i.sstatic.net/J4Iq4.png when trying to embed the snippet? (No errors in the external Fiddle) Added tether.js but no luck (kept it commented). Switched to jQuery 2.2.1 on th ...

Creating a custom npm package for a specific project

As I work on an npm package named my-library and regularly publish updates to a private npm repository, how can I efficiently test changes without repeatedly releasing new versions? Consider the following scenario: I tweak the code in my-library, but wan ...

What is the best way to pass a parameter with a slash in a GET request using jQuery's .ajax() function?

I'm currently faced with the task of generating a specific URL to make an API call using jQuery's .ajax() function: https://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&zipCode=02144&date=2016-11-26&distance=25& ...

How to delay form submission in JavaScript/jQuery

I'm having an issue with delaying the submission of a form. When I trigger the submit after the delay, it does not send the post values. Here is my HTML code: <form id="form_anim" name="form" autocomplete="off" action="index.php" method="POST"> ...

jQuery load() issue

$('form.comment_form').submit(function(e) { e.preventDefault(); var $form = $(this); $.ajax({ url : 'inc/process-form.php', type: 'POST', cache: true, data:({ comment ...