繁体   English   中英

未定义的数据从子组件传递到父组件

[英]Data passed as undefined from child to parent component

我正在子组件中进行文件选择,一旦选择了文件,我想将选定的文件传递给父组件。 我不知道该怎么做。 请帮忙。 如果我尝试打印 onDocumentSelected(value) 中的值,则结果是未定义的。

错误消息属性或方法“值”未在实例上定义,但在渲染期间被引用

父组件

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

子组件

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

摆脱你的 watch 方法并移动onFileSelected内部的逻辑:

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

然后,在父级中,监听document-selected事件:

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

然后,您可以访问该值来做您想做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM