0

我正在尝试将我的 v-for 值(城市)发送到父组件。

<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>

父组件看起来像这样

<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>

切换事件工作正常,我的城市也得到渲染。尽管尝试了几种组合,但我似乎无法将城市名称传递给我的父组件。

4

1 回答 1

1

这应该可以解决问题。

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>
于 2021-11-06T21:03:52.547 回答