I think it's easier for you to just see the relevant VueJS code and then I can explain it:
new Vue({
el: '#app',
data: {
history: [
{name: 'red', value: '#f00'},
{name: 'not red', value: '#ff0'},
{name: 'also not red', value: '#f0f'},
],
},
components: {
ColorItem: {
template:
`<div>
<input :value="name">
<div class="color-preview" :style="{backgroundColor:hex}"></div>
<span v-html="hex"></span>
<button @click="$emit('remove')">
<i class="fas fa-trash"></i>
</button>
</div>`,
props:
['mode', 'hex', 'name'],
methods: {
removeColor: function(index) {
console.log(index);
this.history.splice(index, 1);
}
},
}
},
// ...
}
I have objects (representing colors with names and values) in an array in a variable called history
in my Vue app. I'm using v-for
to create a new color-item
component for each item in history:
<div v-for="(item, index) in history" :key="item.value">
<color-item mode="history" :name="item.name" :hex="item.value" @remove="removeColor(index)">
</color-item>
</div>
I'm trying to delete the color from the list, and I saw this beautiful example of how to use vue to remove items from a list, and it uses their position and splices it. I also saw this SO answer on getting the position using the map function, however pos
is undefined for me, because e.hex
is undefined, and using the inspector I think it's because Vue uses some sort of getter under the hood and doesn't just have the data there for me.
Before someone tells me to use the component template in the v-for loop, I need the template so I can reuse this for other lists of colors (for example, favorites).
I'm very new to Vue so pardon my improper wordings, and I appreciate all the help I can get learning this framework.