Im doing a little blog project to practice vue.js. Im using composition API script setup. When you write a post it saves in localStorage. When you click on the text in the blog it opens up an overlay and a big sized blogtext. its just that its not only showing the one I clicked on but the other earlier blog posts aswell. How can I focus so it only shows the one I click on. Im using tailwind as css.
On this link you can test yourself but here I have some dummytext in before I made it so the note.text will be shown;
CodePudding user response:
Here's a method you can use for conditional rendering.
When dealing with v-loops
without using a child component, you can use index
in the loop then conditionally render it with v-if="selectedIndex = index
.
In the modal section, you add the v-if
like this
<div
v-if="showModal"
@click="showModal = false"
>
<div
v-for="(note, index) in notes"
:key="note.id"
>
<p v-if="selectedIndex === index">{{ note.text }}</p>
</div>
</div>
then in the place where you rendered the text to be clicked, you add a click event to update selectedIndex
when you click on different rendered contents with their relevant index.
<div
v-for="(note, index) in notes"
:key="note.id"
@click="selectedIndex = index"
>
<div
>
...
</div>
</div>
then in the script tag, just add a ref of the selectedIndex
const selectedIndex = ref(null)
Note:
If your @click="showModal = true"
is faster than the selectedIndex update, you will get a "delayed" update. To fix this you want to convert the @click="showModal = true"
into a function, which includes the updateIndex
and this showModal
reassigning.
It would look something like this
<template>
// other parts...
<p @click="updateValues(index)" > {{ note.text }}</p>
// other parts...
</template>
<script setup>
// ... your other functions above
const updateValues = (index) => {
selectedIndex.value = index
showModal.value = true
}
</script>
Anyhow, I think it would be better to split those 2 items (the modal and the render text) into different components, that way you will be able to have an easier time handling the logic.