简体   繁体   中英

Data not emitted from child to parent component in Vue.js

Below are the child and parent components. I am not able to figure out where i am going wrong, but I am not able to pass value data from child to parent component. Please help me find where I am going wrong.

Child Component

<template>
  <div>
    <v-btn class="red-button" @click.prevent="checkAgent('information')">
      Information      
    </v-btn>
    <v-btn class="red-button" @click.prevent="checkAgent('policies')">
      Policies
    </v-btn>
  </div>
</template>


<script>

  export default {
  data: function () {
    return {
    }
  },

  methods: {
    checkAgent(value) {
      this.$emit('navigate', value);  
    },
  }
};
</script>

Parent Component

<template>
  <v-layout row wrap>
    <v-flex xs12 sm12 lg12 >
      <div class="account-section">
        <Details @navigate="moveTo(value)"/>
      </div>
    </v-flex>
  </v-layout>          
</template>

<script>
  import Details from 'views/agent/edit.vue';
  

  export default {
    components: {
      Details,
    },
    data: function () {
      return {
      }
    },
    methods: {
      moveTo(value) {
        console.log(value)
      },
    },
    
  };
</script>

You should call the emitted event handler without specifying the parameter in the template:

   <Details @navigate="moveTo"/>

method:

   methods: {
      moveTo(value) {
        console.log(value)
      },
    },

From Vue Guide , you can access the emitted event's value with $event .

If the event handler is one method and without specifying any parameters, Vue will pass the emitted value as the first parameter of that method .

So for you codes,

one fix will be <Details @navigate="moveTo($event)"/> .

another fix will be <Details @navigate="moveTo"/> same as the answer of @Boussadjra Brahim.

Below is one simple demo for first fix:

 Vue.component('sidebar',{ template:` <div> <button class="btn btn-info" v-on:click="$emit('increment-btn', 1)">Increment on click</button> </div> ` }) new Vue ({ el:'#app', data:{ increment:0 }, methods: { getUpdated: function (newVal) { this.increment += newVal } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app"> <div class="container"> <div class="col-lg-offset-4 col-lg-4"> <sidebar v-on:increment-btn="getUpdated($event)"></sidebar> <p>{{ increment }}</p> </div> </div> </div>

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