Different boolean variable assigned to every item in v-for loop

I am working on creating a custom play/pause button for my audio elements, and here is how I have implemented it:

<div v-for="(post, p) in post_list">
    <!-- ... -->
    <!-- ... -->
    <!-- ... -->
    <v-avatar v-if="!is_played" color="#663399" size="42" class="mx-2"
        @click="playMe('custom-wave-aud-'+p)"> <!-- is_played = true -->
            <v-icon dark> mdi-play </v-icon>
     </v-avatar> 

     <v-avatar v-if="is_played" color="#663399" size="42" class="mx-2"
        @click="pauseMe('custom-wave-aud-'+p)"> <!-- is_played = false-->
            <v-icon dark> mdi-pause </v-icon>
     </v-avatar> 
</div>

When the above code is executed, it switches between the pause icon and play icon when clicked. However, the issue arises as it affects all play/pause buttons for all items due to is_played being assigned globally.

I aim to make is_played impact only one item and be exclusive to the particular item where I toggle the play/pause button.

UPDATE: For reference, here is the play/pause function

playMe(c, index) {
        document.getElementsByClassName(c)[0].play();
        this.is_played = true;
    },
    pauseMe(c, index) {
        document.getElementsByClassName(c)[0].pause();
        this.is_played = false;
    },

Answer №1

To ensure that only the current post's button is affected when the is_played status changes, you need to reference the index of the post within is_played. Here is a simple code snippet to achieve this:

<div v-for="(post, p) in post_list" :key="p">
  <v-avatar v-if="is_played !== p"
            color="#663399"
            size="42"
            class="mx-2"
            @click="playMe('custom-wave-aud-' + p, p)">
    <v-icon dark>mdi-play</v-icon>
  </v-avatar>
  <v-avatar v-if="is_played === p"
            color="#663399"
            size="42"
            class="mx-2"
            @click="pauseMe('custom-wave-aud-' + p, p)">
    <v-icon dark>mdi-pause</v-icon>
  </v-avatar>
</div>
data: () => ({
  is_played: null
}),
methods: {
  playMe(className, index) {
    if (this.is_played !== null) {
      // pause the currently playing one first
      this.pauseMe(className, this.is_played);
    }
    this.is_played = index;
    document.getElementsByClassName(className)[0].play();
  },
  pauseMe(className, index) {
    this.is_played = null;
    document.getElementsByClassName(className)[0].pause();
  }
}

Note: If you want multiple wavs to play simultaneously, you will need to change is_playing to an array and adjust the condition to check if the current index is in the array. Remember to add/remove the index from the array when playing/pausing.

If you require further assistance, please provide a runnable minimal reproducible example.

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

Redux Persist causes the redux state to become undefined

I recently added redux-persist to my project and now I am facing an issue where all of my Redux states are returning undefined. Previously, all the Redux states were functioning properly. However, after incorporating redux-persist, they are no longer work ...

Does this task require a high amount of CPU resources for Node.js on the back-end?

I am currently developing an Android app and I am faced with a decision on whether to utilize node.js or PHP for the back-end. The task at hand involves users inputting query parameters, such as zip codes, which are then used to perform database queries ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

Executing a php function upon onchange event triggered by CKEditor

My task involves invoking a PHP function when I suspect it is being triggered by an ajax call. Utilizing ckeditor, I aim to detect any keyboard activity and believe that using onchange will serve this purpose. Subsequently, I plan to execute a function t ...

Is there a way to incorporate electron methods within Svelte files, specifically in Svelte 3, or is there an alternative approach to achieve this integration?

Currently, I am deep into a project that involves Svelte 3 and Electron 12.0.5 working together harmoniously. For managing hash routing, I have integrated the svelte-spa-router package into my setup. Here is a glimpse of how my project structure appears: n ...

Is there a way to dynamically alter the content depending on the index of the current slide using swiper.js?

Hi, I am new to utilizing the Swiper framework and so far, it has been one of the best sliders I have ever experienced. Currently, I am trying to establish a connection between 2 div tags - one tag holds the content of each slide while the other tag contro ...

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

Issue: Unable to locate module - Unable to resolve 'core-js/modules/es.error.cause.js'

I've incorporated Vuexy Dashboard into my project, which utilizes Vue 2. Now, I'm in the process of upgrading it to Vue 3. However, I have encountered an error that has me stuck. Any assistance with this issue would be greatly appreciated. Thank ...

Unlocking fashion with $refs: A step-by-step guide

After using console.log(this.$refs['block' + row + column]);, I confirmed that I can successfully access the HTML element it refers to. https://i.stack.imgur.com/7KYqB.png However, when attempting to access the element's style using variou ...

Angular $watch | obtaining the result from a function

I'm curious why I consistently have to use this $scope.$watch( function() { return $scope.someData; }, function( value ) { console.log( value ); }); in Angular in order for it to watch the data. It's frustrating to me because it seems un ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

AngularJS is patiently anticipating the population of the scope for ng-show

I have implemented ng-show to display an error message based on an array. The code I used is ng-show="!items.length". However, since the items are populated after a request, there is a flickering effect for a brief moment before the items are loaded. Is th ...

GraphQL Shield throws an 'Unauthorized' error for a permitted mutation

I've been working on setting up a GraphQL API with apollo-server-express, and I'm trying to handle permissions using graphql-shield middleware. However, I'm running into some issues when it comes to allowing mutations to be executed. My aim ...

sw-precache-webpack-plugin for webpack's default service worker template

When utilizing the sw-precache-webpack-plugin to create a service worker for my project, I've noticed that while all my fonts, js, and css files are stored in the cache storage, the index/html file is missing. This has resulted in it not functioning p ...

Utilize JavaScript conditions to dynamically apply styles within your web application

I am facing a challenge with managing two separate <style> tags that each contain a large number of styles and media queries. The issue is that one set of styles is intended for desktop users, while the other is meant for mobile users. When both se ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...