[Vuejs]-Only select post Im clicking on (v-for @click vue.js) but its selecting all saved posts because of the v-for, what can I use instead?

0👍

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" 
  class="absolute w-screen h-screen bg-black opacity-75 z-10 flex cursor-pointer items-center justify-center"
>
    <div 
      v-for="(note, index) in notes" 
      :key="note.id" 
      class="bg-white hover:border-red-400 p-4 rounded-full text-2xl font-bold"
    >
      <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"
  class="border-2 border-slate-100 rounded-3xl hover:border-red-400"
  @click="selectedIndex = index"
> 
   <div 
      class="relative flex flex-col m-0 justify-around cursor-pointer"
   >
     ...
   </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)" class="text-left p-3.5 text-sm"> {{ 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.

Leave a comment