vue.jsnuxt.jsv-forvue-events

How to emit v-for value?


I'm trying to emit my v-for value (city) to a parent component.

<ul class="cards">
  <li v-for="city in cities" :key="city">
    <span  @click="$emit('update-city', city">
      <p @click="$emit('update-toggle')">{{item}}</p>
    </span>
  </li>
</ul>

The parent component looks like this

<template>
<span @update-city ="updatedCity = city">
    <vertical-slider @update-toggle ="toggled= !toggled"  :cities="citiesArray" v-if="toggled">
    </vertical-slider>
  </span>
  
  <p>{{city}}</p>
</template>

<script>
  data(){
    return{
      toggled: false,
      updatedCity: "city",
      citiesArray[City1, City2, City3]
  }
</script>

The toggled event works fine and my cities get rendered as well. I just can't seem to be able to pass the city name to my parent component despite trying several combinations.


Solution

  • This should do the trick.

    index.vue

    <template>
      <div>
        Updated city:
        <pre>{{ updatedCity }}</pre>
        <VerticalSlider
          v-if="toggled"
          :cities="citiesArray"
          @update-city="updatedCity = $event"
          @update-toggle="toggled = !toggled"
        />
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          toggled: true,
          updatedCity: { id: 99, name: 'city' },
          citiesArray: [
            { id: 1, name: 'New York' },
            { id: 2, name: 'Paris' },
            { id: 3, name: 'London' },
            { id: 4, name: 'Istanbul' },
            { id: 5, name: 'Berlin' },
            { id: 6, name: 'Barcelona' },
            { id: 7, name: 'Rome' },
            { id: 8, name: 'Amsterdam' },
            { id: 9, name: 'Munich' },
            { id: 10, name: 'Prague' },
          ],
        }
      },
    }
    </script>
    

    VerticalSlider.vue

    <template>
      <ul class="cards">
        <li v-for="city in cities" :key="city.id">
          <span @click="$emit('update-toggle')">
            <p @click="$emit('update-city', city)">{{ city }}</p>
          </span>
        </li>
      </ul>
    </template>
    
    <script>
    export default {
      name: 'VerticalSlider',
      props: {
        cities: {
          type: Array,
          default: () => [],
        },
      },
    }
    </script>