Consider a scenario where there is a main instance, a child component named "movie-card," and another child component within "movie-card" called "link-btn." The objective is to create a selector that loops through the "link-btn" component using v-for. Additionally, there should be a button in the main instance that displays the data selected from each "link-btn" component. Below is the code snippet:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>Test</title>
</head>
<body>
<div id="app">
<movie-card
v-for="(movie, index) in movies"
key="index"
:movie="movie"
:title="movie.title"
:description="movie.desc"
:review="movie.review">
</movie-card>
<a>BUTTON TO SHOW REVIEWS SELECTED</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="275152425f671509130917">[email protected]</a>/dist/vuex.js"></script>
<script src="app.js"></script>
</body>
</html>
JavaScript:
Vue.component('movie-card', {
props: ['movie', 'title', 'description', 'review'],
template: `
<div>
<h2>{{ title }}</h2>
<p>{{ description }}</p>
<link-btn
v-for="(review, index) in movie.reviews"
:index="index"
:review="review"
key="review"
@updateIndex="updateI($event)"
@updateReview="updateR($event)">
</link-btn>
<pre>{{ $data }}</pre>
</div>
`,
data() {
return {
selectedIndex: '',
selectedReview: ''
}
},
methods: {
updateI(e) {
if(e + 1 === this.selectedIndex) {
this.selectedIndex = ''
} else {
this.selectedIndex = e + 1
}
},
updateR(e) {
if(e.id === this.selectedReview.id) {
this.selectedReview = ''
} else {
this.selectedReview = e
}
}
}
})
Vue.component('link-btn', {
props: ['index', 'review'],
template: `
<a @click="change">{{ review.content }}</a>
`,
methods: {
change() {
this.$emit('updateIndex', this.index)
this.$emit('updateReview', this.review)
}
}
})
new Vue({
el: '#app',
data: {
added: [],
movies: [
{
title: 'Back to the Future',
desc: 'This is the description of Back to the Future',
reviews: [
{ id: 1, content: 'Blabla...', stars: 2, active: false },
{ id: 2, content: 'Blabla...', stars: 3, active: false },
{ id: 3, content: 'Blabla...', stars: 1, active: false }
]
},
{
title: 'Titanic',
desc: 'This is the description of Titanic',
reviews: [
{ id: 1, content: 'Blabla...', stars: 2, active: false },
{ id: 2, content: 'Blabla...', stars: 3, active: false },
{ id: 3, content: 'Blabla...', stars: 1, active: false }
]
},
{
title: 'Blade Runner',
desc: 'This is the description of Blade Runner',
reviews: [
{ id: 1, content: 'Blabla...', stars: 2, active: false },
{ id: 2, content: 'Blabla...', stars: 3, active: false },
{ id: 3, content: 'Blabla...', stars: 1, active: false }
]
}
]
}
})