I want to render the content of requestData to li elements
each list item gets a onclick function
which if the li element is clicked(selected) adds a specific value from a ref to an array
later if clicked again(unselected) delets the item /
how can I combine the function output true / false
to :class="{ selected: requestData }" to add or remove the class if selected/unselected
<template>
<section>
<ul>
<li
v-for="item in requestData.items"
:key="item.id"
:class="{ selected: requestData }"
@click="getSelectedElemData($event.target)"
>
{{ item.name }}
</li>
</ul>
</section>
</template>
<script>
import { onMounted, ref } from "@vue/runtime-core";
import items from "../assets/comp.Data/items.json";
export default {
setup() {
let requestData = ref(items);
let selectedElements = [];
function getSelectedElemData(target) {
for (let element of requestData._rawValue.items) {
if (target.innerText === element.name) {
console.log(element);
// Add to calc
// update the selectedElements array
selectedElements.push(element);
console.log(selectedElements);
return true;
}
}
}
return {
requestData,
getSelectedElemData,
};
},
};
</script>
You can try using this apporach and call isItemSelected function for each element. If the item is included in the list, class we added to the li otherwise it will be removed. And change the isItemSelected function accordingly to your current data set, below approach it is for array of objects.
<template>
<section>
<ul>
<li
v-for="item in requestData.items"
:key="item.id"
:class="{ 'selected': isItemSelected(item) }"
@click="getSelectedElemData($event.target)"
>
{{ item.name }}
</li>
</ul>
</section>
</template>
<script>
import { onMounted, ref } from "@vue/runtime-core";
import items from "../assets/comp.Data/items.json";
export default {
setup() {
let requestData = ref(items);
let selectedElements = [];
function getSelectedElemData(target) {
for (let element of requestData._rawValue.items) {
if (target.innerText === element.name) {
console.log(element);
// Add to calc
// update the selectedElements array
selectedElements.push(element);
console.log(selectedElements);
return true;
}
}
}
function isItemSelected(item){
return selectedElements.find(element=>element.id===item.id)
}
return {
requestData,
isItemSelected,
getSelectedElemData
};
},
};
</script>