I will need more help, because I only have basic knowledge in JavaScript and I have been worried about it for 3 days and I can't put it together. I know I ask a lot but I am stuck and I have no idea how to make it works. I want the following:
<div >
<div >
<!-- here i want display all used tags -->
</div>
<div >
<img />
<!-- here i want display all images which contains selected tags -->
</div>
</div>
Defined in code I have this as follows
data: function () {
return {
images: [
{
tags: ["art"],
url: "url of image",
name: "my image name",
},
{
tags: ["chipmunk", "art"],
url: "url of image",
name: "my image name",
},
{
tags: ["ship"],
url: "url of image",
name: "my image name",
},
{
tags: ["art", "ship"],
url: "url of image",
name: "my image name",
},
],
};
},
};
I want:
1. A feature that automatically searches for this images Array and finds all tags and displays them in .tags
as <li>
each. Selectable and each only once and sorted alphabet) without having to write them in my own Array.
2. A feature that automatically displays all images that contain a selected tag
CodePudding user response:
If I understood you correctly, try like following snippet:
const app = Vue.createApp({
name: 'size guide app',
data() {
return {
images: [
{
tags: ["art"],
url: "https://picsum.photos/200",
name: "my image name",
},
{
tags: ["chipmunk", "art"],
url: "https://picsum.photos/201",
name: "my image name",
},
{
tags: ["ship"],
url: "https://picsum.photos/199",
name: "my image name",
},
{
tags: ["art", "ship"],
url: "https://picsum.photos/202",
name: "my image name",
},
],
tags: [],
selected: []
}
},
mounted() {
const set = new Set([])
this.images.forEach(i => {
set.add(...i.tags)
})
this.tags = [...set]
},
computed: {
getItems() {
return this.images.filter(i => {
return this.selected.some(s => i.tags.includes(s) )
})
}
},
methods: {
selectTag(tag) {
!this.selected.includes(tag) && this.selected.push(tag)
}
}
})
app.mount('#demo')
.tags, .container {
display: flex;
column-gap: 1em;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div >
<template v-for="tag in tags">
<button @click="selectTag(tag)">{{ tag }}</button>
</template>
</div>
<div v-if="selected.length">
<template v-for="sel in selected">
<p>{{ sel }}</p>
</template>
</div>
<div >
<div v-for="img in getItems">
<p>{{ img.name }}</p>
<img :src="img.url" />
<p>{{ img.tags }}</p>
</div>
</div>
</div>
CodePudding user response: