Hitendra
Hitendra

Reputation: 3236

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?

Upvotes: 4

Views: 16905

Answers (2)

Hiren Gohel
Hiren Gohel

Reputation: 5041

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!

Upvotes: 13

Raj
Raj

Reputation: 415

Say I have a page with this HTML.

<div class="select-all">
    <input type="checkbox" name="all_select" id="all_select">
    <label @click="checkchecker" for="all_select"></label>
</div>

the function checkchecker is called in my methods

 checkchecker() {
      this.checker = !this.checker
    }

This will show or hide my div on that page like this

<div v-show="checker === true" class="select-all-holder">
  <button>Select All</button>
</div>

Now if I also want to toggle another div which is inside my child component on that page I will pass the value like this.

<div class="content-section clearfix">
   <single-product :checkers="checker"></single-product> //This is calling my child component
</div>

Now in my Child component I will have a prop declared like this

checkers: {
  type: String,
  default: false,
},

This is how I will write my div in my child component

<div v-show="checkers === true" class="select-holder clearfix">
      <input type="checkbox" class="unchecked" name="single_select" id="1">
    </div>

Upvotes: -1

Related Questions