[Vuejs]-Toggle custom audio play/pause button inside v-for

0👍

You should split the codes inside the v-for into a new component called avatar-item for example:

<div v-for="(post, p) in post_list">
    ...
    ...
    ...
    <avatar-item></avatar-item>
</div>

Then your avatar-item component will look like this:

<template>
    <div>
        <v-avatar v-if="!is_played" color="#663399" size="42" class="mx-2"
            @click="playMe('custom-wave-aud-'+p)">
                <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)">
                <v-icon dark> mdi-pause </v-icon>
        </v-avatar> 
    </div>
</template>

Move the variable is_played into this component as well as your other functions:

<script>
export default {
    data() {
        return {
            is_played: false,
        }
    },
    methods: {
        playMe(c) {
            document.getElementsByClassName(c)[0].play();
            this.is_played = true;
        },
        pauseMe(c) {
            document.getElementsByClassName(c)[0].pause();
            this.is_played = false;
        },
    }
}

</script>

By this, each component will have a independent is_played variable, so it should be toggled independently.

Leave a comment