【问题标题】:$refs is undefined - Custom File Input button referencing issue$refs 未定义 - 自定义文件输入按钮引用问题
【发布时间】:2020-12-15 01:01:30
【问题描述】:

我有一系列基于车辆数据和相关图像的卡片。我想为每张卡片添加一个自定义上传图片按钮,但存在引用问题。

使用标准输入类型文件,如果我从输入中选择 Browse 则可以:

<v-col v-for="item in vehicles" :key="item.id">
    <v-card class="mx-auto" outlined>
        <input 
            type="file"
            @change="uploadImage"
            accept="image/*"
            :ref="`imageInput${item.id}`"
        >
    </v-card>
</v-col>

但是我想使用自定义按钮。如果我隐藏输入并添加一个按钮使用:

        <input 
            type="file"
            @change="uploadImage"
            accept="image/*"
            :ref="`imageInput${item.id}`"
            class="d-none"
        >

       <v-btn @click="$refs.imageInput[item.id].click()">Upload photo</v-btn> 

然后单击 v-btn 我得到一个错误,因为我没有正确引用它。任何关于应该如何完成的指针?

使用方法:

<v-btn @click="buttonClicked(item.id)">Upload photo</v-btn>

methods:{
    buttonClicked(itemId) {
        let ref = `imageInput${itemId}`
        console.log('ref: ', ref)
        let element = this.$refs[ref]
        console.log('element', element)
        element.click()
    }

我得到错误:

Error in v-on handler: "TypeError: element.click is not a function"

【问题讨论】:

    标签: vue.js vuetify.js


    【解决方案1】:

    当 item id 为 4 时,您的 ref 将输出这样的字符串

    imageInput4
    

    在您的v-btn 中,您尝试按索引访问该项目,它应该看起来像这样

    $refs[`imageInput${item.id}`]
    

    不过我建议将该调用转移到一个方法中,这样会很容易调试

    buttonClicked(itemId) {
        let ref = `imageInput${itemId}`
        console.log('ref: ', ref)
        let element = this.$refs[ref]
        console.log('element', element)
        element.click()
    }
    

    【讨论】:

    • 恐怕两者都不起作用:1) _vm.$refs[("imageInput" + item.id)].click 不是函数2) v-on 处理程序中的错误:“TypeError: element.点击不是函数”
    • @RGriffiths 请发布您看到的错误。我在本地重新创建了它,它可以工作
    • 你是在建议 $refs[imageInput${item.id}].click()
    • @RGriffiths @click="$refs[`imageInput${item.id}`].click()"
    • 如果我使用 element[0].click() - 返回的元素是一个数组 - 它似乎工作。谢谢。遗憾的是它不想与描述方法一起工作。对我来说似乎有点笨拙,但我是 Vue 的新手,刚刚开始学习。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2019-02-23
    • 2018-06-16
    • 1970-01-01
    相关资源
    最近更新 更多