如何在vuejs中为父组件的子组件元素设置$ ref?

时间:2019-06-19 06:03:20

标签: vue.js vue-class-components

这是父组件:

<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(); 但是,当我将文件输入移动到父组件时,就可以正常工作。因此,您能帮助我如何设置对父对象的子组件元素的引用,因为当前未设置。 谢谢

1 个答案:

答案 0 :(得分:2)

好吧,您可以在父组件的ref上添加upload-block

<upload-block ref="upload" ... >

然后在handleUploadIcon中,您可以输入:this.$refs.upload.$refs[icon_type]

但是如果我是我,我会尝试将handleUploadIcon移至子组件。