I am currently developing an app that reveals a div when clicked. However, if someone clicks on another button to open a different div, I want the previously opened div to hide automatically. While I have managed to achieve this functionality by manually setting this.movies[index].open = false
and
this.movies[index].hideImg = true
, it would become impractical with thousands of entries. This is where the toggle(id)
method comes into play.
<template>
<div v-for="(movie, index) in movies" :key="index" class="movieContainer">
<div class="center">
<h3>{{ movie.name }}</h3>
<p class="duration">{{ movie.duration }}</p>
<button @click="toggle(movie.id)" class="watchBtn">
<p v-if="movie.hideImg">►</p>
<p v-else>▼</p>
</button>
</div>
<div v-if="movie.open">
<video controls="controls" autoplay name="media">
<source
:src="require(`@/assets/movie${index + 1}.mp4`)"
alt="video"
type="video/mp4"
width="500px"
autoplay
/>
</video>
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
movies: [
{
name: "Windy Highway",
duration: "15 seconds",
hideImg: true,
open: false,
id: 1,
movieStart: "0:00",
movieMid: "0.08",
movieEnd: "0:15",
},
{
name: "Sunny Station",
duration: "32 seconds",
hideImg: true,
open: false,
id: 2,
movieStart: "0:00",
movieMid: "0.16",
movieEnd: "0:32",
},
{
name: "Abstract Material",
duration: "9 seconds",
hideImg: true,
open: false,
id: 3,
movieStart: "0:00",
movieMid: "0.05",
movieEnd: "0:09",
},
{
name: "Pumpkin Drilling",
duration: "17 seconds",
hideImg: true,
open: false,
id: 4,
movieStart: "0:00",
movieMid: "0.09",
movieEnd: "0:17",
},
],
};
},
methods: {
toggle(id) {
for (let i = 0; i < this.movies.length; i++) {
this.movies[i].open = false;
this.movies[i].hideImg = true;
}
this.movies[id - 1].hideImg = !this.movies[id - 1].hideImg;
this.movies[id - 1].open = !this.movies[id - 1].open;
console.log(
this.movies[id - 1].movieStart,
"-",
this.movies[id - 1].movieMid,
"-",
this.movies[id - 1].movieEnd
);
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin: 60px auto 0;
}
.watchBtn {
background-color: red;
border-radius: 10px;
margin-left: 10px;
height: 20px;
display: flex;
align-items: center;
}
.watchBtn:hover {
background-color: rgb(255, 191, 107);
cursor: pointer;
}
.movieContainer {
margin: 5px auto;
display: flex;
flex-direction: column;
}
.center {
margin: 0 auto;
display: flex;
align-items: center;
}
.duration {
margin: 0 5px 0 10px;
}
.movieContainer video {
width: 500px;
}
</style>
Link to the code on StackBlitz