Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from one component to other in vue js?

I am learning vue+laravel. I want to pass value from one component to other component? I have used vue router for routing.

Here is the code for first and second component. SelectPerson.vue

<template>
    ......
      <div>
        <input type="number" class="form-control" name="numberOfPersons" placeholder="Enter number of persons here" **v-model="inputPersons"**>
        <br>
        **<SelectTimeSlot v-bind:numberOfPersons="inputPersons"></SelectTimeSlot>**
      </div>
      <div>
        <button class="btn btn-default float-right mt-2" v-on:click="selectTimeSlots">Next</button>
      </div>
    ......
</template>
<script>
import SelectTimeSlot from './SelectTimeSlot.vue'
  export default{
    props:['numberOfPersons'],
    data(){
        return{
          **inputPersons:0**
        }
    },
    methods:{
      selectTimeSlots(){
        this.$router.push({name:'SelectTimeSlot'});
      }
    }
  }
</script>

second component SelectTimeSlot.vue

<template>
<h5>Welcome, You have selected **{{numberOfPersons}}** persons.</h5>
</template>

Can anybody help me do it?

like image 459
Hitendra Avatar asked Dec 13 '22 20:12

Hitendra


1 Answers

To pass data from one component to other component, you need to use props:

First component:

<second-component-name :selectedOption="selectedOption"></second-component-name>

<script>
export default {

   components: {
        'second-component-name': require('./secondComponent.vue'),
   },
   data() {
        return {
          selectedOption: ''
        }
    }
}
</script>

Second Component:

<template>
    <div>
        {{ selectedOption }}
    </div>
</template>

<script>
    export default {
        props: ['selectedOption']
    }
</script>

Please visit this link.

Hope this is helpful for you!

like image 112
Hiren Gohel Avatar answered Dec 18 '22 06:12

Hiren Gohel