vue父组件中获取子组件中的数据(实例讲解)

如下所示:

<FormItem label="上传头像" prop="image">
   <uploadImg :width="150" :height="150" :name="'avatar'" size="150px*150px" ref="avatar"></uploadImg>
</FormItem>
 <FormItem label="上传营业执照" prop="businessLicence">
 <uploadImg :width="350" :height="200" :name="'businessLicence'" size="350px*200px" ref="businessLicence"></uploadImg>
</FormItem>

自己写了个上传图片的子组件,父组件需要获取到子组件上传的图片地址,

方法一:给相应的子组件加ref

父组件在最后提交的时候获取thi.$ref.avatar.相应数据即可,因为在这里才能保证图片已经上传,否则如果图片没上传,拿到的值一定为空。

方法二:$emit()

/*
  子组件
*/
<template>
  <input type='file' @change="changeUrl" />
</template>
<script>
export default {
  methods: {
    changeUrl(e) {
      this.$emit('changeUrl', e.currentTarget.files[0].path)
    }
  }
}
</script>
/*
  父组件
*/
<template>
  <FormItem label="上传营业执照" prop="businessLicence">
    <uploadImg :width="350" :height="200" :name="'license'" size="350px*200px" @changeUrl="getUrl"></uploadImg>
  </FormItem>
</template>
<script>
export default {
  methods: {
    getUrl(path) {
      //这个就是你要的path,并且会双向绑定
    }
  }
}
</script>

以上这篇vue父组件中获取子组件中的数据(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。