简体   繁体   中英

Data passed as undefined from child to parent component

I am making a file selection in the child component and once file is selected I want to pass the selected file to the parent component. I am not able to figure out how to do that. Please help out. If I try to get the print the value inside the onDocumentSelected(value) it comes out to be undefined.

Error message Property or method "value" is not defined on the instance but referenced during render

Parent Component

<template>
  <v-form :model='agency'>
    <DocumentSelect 
       type="file"
       ref="file"
       :required="true"
       name="vue-file-input"
       @change="onDocumentSelected(value)"
    />
  </v-form>
</template>

<script>
  import DocumentSelect from 'views/document-selection.vue';

export default {
  components: {
    DocumentSelect
  },
  props: ['agency'],
  methods: {
    onDocumentSelected(value) {
      console.log(value); //undefined
    },
  }
};
</script>

Child Component

<template>
  <div class="input-group input-group--select primary--text" :class="{'input-group--required': required, 'input-group--error': hasError, 'error--text': hasError}" >
     <div class="input-group__input">
       <input
          type="file"
          name="name"
          ref="file"
          @change="onDocumentSelected" />
     </div>
      <div class="input-group__details">
        <div class="input-group__messages input-group__error" v-for="error in errorBucket">
          {{error}}
        </div>
      </div>
   </div>
</template>

<script>
  import Validatable from  'vuetify/es5/mixins/validatable.js'

  export default {
    mixins: [Validatable],
    props: ['type', 'name', 'required'],
    data: function () {
      return {
        inputValue: ''
      };
    },
    watch: {
      inputValue: function(value) {
        this.validate();
        console.log(value); // *Event {isTrusted: true, type: "change", target: input, currentTarget: null, eventPhase: 0, …}*
        this.$emit('change', {value});
      },
    },
    methods: {
      onFileSelected(event) {
        this.inputValue = event
      },
    },
  };
</script>

Get rid of your watch method and move the logic inside onFileSelected :

@change="onFileSelected($event)"
onFileSelected(e) {
  this.validate();
  this.$emit('document-selected', e);
}

Then, in the parent, listen for the document-selected event:

<DocumentSelect 
       type="file"
       ref="file"
       :required="true"
       name="vue-file-input"
       @document-selected="onDocumentSelected($event)"
/>

You then have access to that value to do what you want with.

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