in my little local vuejs-project (script setup) i'm receiving dummy-data (getTutorials) from my api (symfony, api plattform). The dummy-data have a value "true" or "false" from Database-Column "published". Dummy-Data in Database
What i have: 2 columns:
- Left Column: Published
- Right Column: Unpublished
what i want:
- v-for loop for all Data with boolean "true" in the left Column.
- v-for loop for all Data with boolean "false" in the right Column.
what i have:
- all data ("true" and "false") are in the left Column.
- no data (with "false") in the right Column.
my Code:
<script setup>
import { ref } from "vue";
import TutorialDataService from "../services/TutorialDataService";
const tutorials = ref("");
const getTutorials = TutorialDataService.getAll()
.then((response) => {
tutorials.value = response.data["hydra:member"];
// console.log(response.data["hydra:member"]);
console.log("---Retrieve OK---");
})
.catch((e) => {
console.log(e);
});
</script>
<template>
<div >
<div >Published:
<ul >
<li v-for="item in tutorials" :key="item.id">
{{ item.title }} - <b>{{ item.published }}</b>
</li>
</ul>
</div>
<div >Unpublished:
<ul >
<li v-for="item in filtered" :key="item.id">
{{ item.title }}
</li>
</ul>
</div>
</div>
</template>
what i need: Dont know how to filter this Dummy-Data with computed or a method. Can anyone help me to filter the received dummy-data, that i can make a v-for loop for the right Column?
Thank You Tom
CodePudding user response:
You can use filter in a computed property, like:
const notPublished = computed(() => {
const nP = tutorials.filter(t => {
return t.published === 0; // 0 is not published?
});
return nP;
});
Remember to import computed from vue:
import { ref, computed } from "vue";
You can use notPublished
in your v-for
:
<li v-for="item in notPublished" :key="item.id">
{{ item.title }} - <b>{{ item.published }}</b>
</li>
CodePudding user response:
You just need to filter your data when you get it from api:
const getTutorials = TutorialDataService.getAll()
.then((response) => {
const data = response.data["hydra:member"]; // Saved this into local variable
tutorials.value = data.value.filter((item) => !item.published); // Filter to get all tutorials with published = 0
filtered.value = data.value.filter((item) => !!item.published); // Filter to get all tutorials with published = 1
// console.log(response.data["hydra:member"]);
console.log("---Retrieve OK---");
})
.catch((e) => {
console.log(e);
});
Using !
and !!
operators here, more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT