本次分享的方法,也是在工作中遇到的。特此记录,以备下次遇到方便查看,谁调用谁就是父组件。
通过ref获取dom!
子组件
<template>
<div v-else class="mybox">
<img :src="imageUrl" class="avatar" />
<i class="el-icon-close mycross" @click="clickImg"></i>
</div>
</template>
methods: {
// 点击清空图片
clickImg() {
this.imageUrl = ''
},
}
父组件: 在父组件使用组件的地方中加上ref即可通过this.$refs.ref.method调用
<template>
<div @click="handleClose"></dev?
<UploadWechatImg
@updateWechatImgUrl="updateImgUrl"//自己封装的组件
:type="'image'"
:imgUrl="imgUrl"
@clearImg="clearImg"
@getMyname="getMyname"
ref="child1"//在父组件使用的组件的地方这里添加ref
/>
</template>
<script>
methods: {
handleClose () {
console.log('调用子组件方法', this.$refs.child1)
this.$refs.child1.clickImg(this.$refs.child1.imageUrl == '')
}
}
</script>