简体   繁体   中英

How to pass a prop from parent to child in Vuejs

I have a parent component called Stepper which contains this child component called ShortSummary . I am trying to pass a prop from Stepper to ShortSummary by clicking on a radiobutton. but it doesn't work! Here's what I have done. This is Stepper :

<v-radio-group row v-model="voltage" >
    <v-radio
    v-for="n in radioNames"
    :key="n"
    :label="n"
    :value="n"></v-radio>
</v-radio-group>

<app-short-summary :voltage="voltage" ></app-short-summary>

<script>
import ShortSummary from "./ShortSummary";
    data() {
      return {
        voltage:'',
        radioNames:
        ['24V to 36V',
          '48V to 72V',
          '96V to 110V']
    },
    components:{
      appShortSummary: ShortSummry
    }
}
</script>

and this is ShortSummary :

<v-list-tile
    :key="item.title"
    avatar
    ripple
    @click="toggle(index)">
    <v-list-tile-content>
         {{item.action}}
    </v-list-tile-content>
</v-list-tile>

<script>
export default {
  props:['voltage']
  data () {
    return {
      selected: [2],
      items: [
        {
          action: `Voltage: ${this.voltage}`
        },
        {
          action: 'Weight: POOF'
        },
        {
          action: 'Size: BOOM'
        },
        {
          action: '2oo2? Need the logic document'
        },
        {
          action: 'Price: Very very expensive'
        }
      ]
    }
  },
}
</script>

currently it shows voltage as blank. I want Voltage: ${this.voltage} to show the value of voltage selected from the radiobutton on Stepper

Component's data object is initialized before this is available, hence this.voltage is undefined.

Instead make your items as computed prop.

<script>
export default {
  props:['voltage']
  data () {
    return {
      selected: [2],
    }
  },
  computed: {
   items() {
     return [
        {
          action: `Voltage: ${this.voltage}`
        },
        {
          action: 'Weight: POOF'
        },
        {
          action: 'Size: BOOM'
        },
        {
          action: '2oo2? Need the logic document'
        },
        {
          action: 'Price: Very very expensive'
        }
      ]
   }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM