vue父组件中获取子组件中的数据

时间:2023-03-09 17:59:13
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 = “avatar”

父组件在最后提交的时候获取this.$refs.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>

2017.12.21更新

当使用this.$emit方法获取的时候,如果子组件想要给父组件传入多个值,则可以写多个参数,父组件在获取的时候获取多个参数的值即可

//父组件
getUrl(path1,path2) {
console.log(path1,path2)
}

注意问题:

1、父组件相应事件写在该子组件上

2、子组件如果并没有click事件触发,也没有类似本例input需要change事件触发,则在created或者mounted函数中让该函数加载即可

3、子组件向父组件传值需 是父组件 用到了 ,如果多个父组件引用了该子组件,则只有传值的时候用的子组件来自哪个父组件,这个父组件才可以接收到值,其他父组件获取不到子组件传的值。