这是父组件:
<template>
<upload-block
:imSrc="LargeIcon"
inputName="LargeIcon"
:inputHandler="uploadAppIcon"
inputRef="LargeIcon"
:uploadClickHandler="handleUploadIcon"></upload-block>
</template>
<script>
export default class ParentCom extends Vue {
//all props for <upload-block></upload-block> component defined here
handleUploadIcon(event) {
const icon_type = event.currentTarget.getAttribute("data-type");
let appImgElem = this.$refs[icon_type];
appImgElem.click();
}
async uploadAppIcon(event) {
//code
}
}
</script>
这是子组件:
<template>
<div class="upload-div" @click="uploadClickHandler" :data-type="inputName">
<img v-if="imSrc" :src="imSrc">
<div v-else class="upload-icon-block">
<span>
<font-awesome-icon class="upload-icon" icon="arrow-circle-up" size="lg"></font-awesome-icon>
<br>Click to upload
</span>
</div>
<!-- <spinner variant="primary" :show="true"></spinner> -->
<input style="display:none" type="file" :ref="inputRef" :name="inputName" @input="inputHandler">
</div>
</template>
<script>
@Component({
props: {
imSrc: String,
inputRef: String,
inputName: String,
inputHandler: Function,
uploadClickHandler: Function
}
})
export default class ChicdCom extends Vue {
}
</script>
我在handleUploadIcon
方法中遇到的问题,其中我无法通过input
获取ref
元素。
该行Cannot read property 'click' of undefined
中显示appImgElem.click();
但是,当我将文件输入移动到父组件时,就可以正常工作。因此,您能帮助我如何设置对父对象的子组件元素的引用,因为当前未设置。
谢谢
答案 0 :(得分:2)
好吧,您可以在父组件的ref
上添加upload-block
:
<upload-block ref="upload" ... >
然后在handleUploadIcon
中,您可以输入:this.$refs.upload.$refs[icon_type]
但是如果我是我,我会尝试将handleUploadIcon
移至子组件。