Currently taking part in Vue.js mini workshops, where I am working with two components named PersonCard and ColorPick, along with a dataset. Each person in the dataset can have their own personalized PersonCard, complete with a color picker (radio buttons). However, I am facing difficulty in retrieving the 'Picked Color' from the ColorPick component back to the PersonCard component for use in styling via style binding. Despite trying to utilize $emit, I have not been successful. Any guidance or suggestions would be greatly appreciated.
I understand that directly accessing and updating updatedPlayers.color may not work as expected since updatedPlayers is an array being iterated over in the template. How can I specify the individual 'player' within updatedPlayers to update their color based on the $emit event?
App.vue
<template>
<div>
<PersonCard :players="players"></PersonCard>
</div>
</template>
<script>
import PersonCard from './components/PersonCard.vue'
export default {
components: {
PersonCard
},
data () {
return {
players: [
{
id: 1,
name: "Daniel",
age: 33,
color:"red"
},
{
id: 2,
name: "Sam",
age: 21,
color: "green"
}
]
}
}
};
</script>
<style scoped>
</style>
PersonCard.vue
<template>
<div>
<li v-for="player in updatedPlayers" :key="player.id">
<h4 :style="{backgroundColor: player.color}">{{player.name}}</h4>
<ColorPick @colorChosen="newColor"></ColorPick>
</li>
</div>
</template>
<script>
import ColorPick from './ColorPick.vue'
export default {
data () {
return {
pickedColor: '',
updatedPlayers : this.Players
}
},
props: ['Players'],
components: {
ColorPick
},
methods: {
newColor (newColor) {
this.updatedPlayers.color = newColor;
}
}
};
</script>
<style scoped>
li {
list-style: none !important;
}
</style>
ColorPick.vue
<template>
<div>
<form action>
<input type="radio" name="nameColor" value="yellow" v-model="pickedColor" @change="colorChosen" /> Yellow
<br />
<input type="radio" name="nameColor" value="red" v-model="pickedColor" @change="colorChosen" /> Red
<br />
<input type="radio" name="nameColor" value="blue" v-model="pickedColor" @change="colorChosen" /> Blue
</form>
</div>
</template>
<script>
export default {
data() {
return {
pickedColor: "",
};
},
methods: {
colorChosen(pickedColor) {
this.$emit ('newColor', pickedColor);
}
}
};
</script>
<style>
</style>