Vue.js中的数据未从子组件发送到父组件

时间:2020-07-30 17:08:29

标签: javascript vue.js vuejs2 vue-component vuetify.js

下面是子组件和父组件。我无法弄清楚哪里出了问题,但是我无法将值数据从子组件传递到父组件。请帮助我找出问题所在。

子组件

<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>

父组件

<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>

2 个答案:

答案 0 :(得分:2)

您应在不指定模板参数的情况下调用发出的事件处理程序:

   <Details @navigate="moveTo"/>

方法:

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

答案 1 :(得分:0)

Vue Guide中,您可以使用$event访问发出的事件的值

如果事件处理程序是一个方法且未指定任何参数,则Vue将传递发出的值作为该方法的第一个参数。

为您编码,

一个修补程序<Details @navigate="moveTo($event)"/>

另一种解决方法将与{Boussadjra Brahim的答案<Details @navigate="moveTo"/>相同。

下面是一个简单的演示程序,用于首次修复:

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>