【问题标题】:How to focus click on input vue如何专注于点击输入vue
【发布时间】:2020-03-18 06:25:50
【问题描述】:

如何使用 onClick 按钮集中输入?

<div class="form-group"
v-for="(file, i) in registerData.requiredDocuments"
:key="`file-${i}`">
   <label for="npwp" class="text-muted"> {{file.name}} </label>
   <input type="file"
   :name="file.name"
   class="form-control-file"
   :id="file.name"
   :accept="file.name === 'Logo' ? `image/png, image/jpg, image/jpeg` : `application/pdf`">
    <div class="d-flex">
      <button class="btn btn-primary" type="button">Choose File</button>
    </div>
</div>

我希望通过单击“选择文件”按钮来触发输入。我试过了

// the input

<input :ref="file.name" type="file">

// the button 

<button @click="$refs.file.name.focus()">Choose File</button>

但我得到的是名称未定义,有人知道如何解决这个问题吗?

【问题讨论】:

    标签: vue.js input vuejs2 html-input


    【解决方案1】:

    我之前也遇到过类似的问题,这里是如何做到的。

    <template>
        <div>
            <div class="form-group" v-for="(file, i) in registerData.requiredDocuments" :key="`file-${i}`">
                <label for="npwp" class="text-muted"> {{file.name}} </label>
                <input type="file" :ref="'file' + i" :name="file.name" class="form-control-file" :id="file.name"
                    :accept="file.name === 'Logo' ? `image/png, image/jpg, image/jpeg` : `application/pdf`">
                <div class="d-flex">
                    <button @click.prevent="setFileFocus(i)" class="btn btn-primary" type="button">Choose File</button>
                </div>
            </div>
        </div>
    </template>
    <script>
    export default {    
        methods: {
            setFileFocus(index) {
                this.$nextTick(function(){
                    this.$refs[("file" + index)][0].focus()
                })
            }
        }
    }
    </script>

    我在nexttick 上致电focus。希望我的回答对你有帮助

    【讨论】:

    • 是的,这正是我所做的,但问题是,ref 绑定到 v-for 并且循环的参数未定义
    • 是的,我明白了。我已经编辑了我的代码 sn-p。现在试试吧,它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2018-09-30
    • 1970-01-01
    • 2019-08-20
    相关资源
    最近更新 更多