I have two arrays:
$globalData.dishesdefined inmain.jsas['Salad', 'Burger', 'Cake'].dishesdefined inApp.vueas an empty array.
The code I’ve written should list all dishes in $globalData.dishes originally in pink. When a dish is clicked, it is added to dishes and its color changes to green (this works). When clicked on again it is removed from dishes and its color reverts back to pink (this does not work).
App.vue:
<template>
<div>
<h2>Dishes:</h2>
<ul>
<li v-for="dish in this.$globalData.dishes" v-bind:key="dish.id"
:style="[dishes.includes(dish) ?
{'background-color': 'lightgreen'} :
{'background-color': 'pink'}]"
@click="addDish(dish)">
{{ dish }}
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
dishes: []
}
},
methods: {
addDish(dish){
if (this.dishes.includes(dish)){
this.dishes.filter((d) => d !== dish)
} else {
this.dishes.push(dish);
}
},
}
}
</script>
main.js:
...
Vue.prototype.$globalData = Vue.observable({
dishes: ['Salad', 'Burger', 'Cake'],
});
...
>Solution :
It looks like the issue is with the addDish method in your App.vue component.
The Array.filter method doesn’t modify the original array, it creates a new array. Therefore, when you try to remove a dish by using this.dishes.filter() method, it creates a new array, but you are not assigning it back to this.dishes.
You need to update your addDish method to correctly remove the dish from the array.
methods: {
addDish(dish){
if (this.dishes.includes(dish)){
this.dishes = this.dishes.filter((d) => d !== dish);
} else {
this.dishes.push(dish);
}
},
}