[Vuejs]-How to get selected option from selected componets in Vue.js?

0👍

I will take a stab at an example showing multiple options, knowing I don’t have the full context of your specific problem, but I am sure this example will get you pointed in the right direction.

I took liberty with object names, and assumed values in JSON objects. Obviously you will ned to adjust this for your specific use case and data.

<template>
  <div class="i-am-the-parent">
    <!-- 
      Display flight from name
     -->
    <div
      v-if="flights.from"
      class="display-text-from"
    >
      {{ flights.from.airportName }}
    </div>
    <SelectFlight
      v-model="flights.from"
      placeholder="from"
    />

    <!-- Bind flight to "airportName" as a prop in parent -->
    <ParentWrapperComponent
      class="display-text-to"
      :airport-name="flights.to ? flights.to.airportName : null"
    >
      <!--
        Nested in ParentWrapperComponent
      -->
      <SelectFlight
        v-model="flights.to"
        placeholder="to"
      />
    </ParentWrapperComponent>

    <!--
      Kitchen Sink
      Here I am demonstrating multiple approaches:
      1. Merge the data via a computed property and pass as a property named airports
      2. Simply pass the flights data property as a flights property
      3. Simply pass the properties "flights.from" data as property "from" and "flights.to" data as property "to"
    -->
    <SomeComponentToShowBoth
      :airports="combineValues"
      :flights="flights"
      :from="flights.from"
      :to="flights.to"
    />
  </div>
</template>

<script>
import SelectFlight from '@/path/to/component/SelectFlight'
export default {
  components: {
    SelectFlight
  },
  data () {
    return {
      flights: {
        from: null,
        to: null
      }
    }
  },
  computed: {
    combineValues () {
      // this will return both json objects merged into one.
      // It will update everytime this.flights.from or this.flights.to changes
      return Object.assign({}, this.flights.from, this.flights.to)
    },
    combineFlightNames () {
      // Perhaps you just want to pass the names?
      return {
        from: flights.from ? flights.from.airportName : null,
        to: flights.to ? flights.to.airportName : null
      }
    }
  }
}
</script>

References:

Leave a comment