1

I try to have a input file button (this is in a v-for loop). But I don't want to use the b-form-file tag.

So I've tried - at least - all things I have seen, but nothing worked out for me.

I have the following code:

<b-button @click="selectFile()" variant="success" :id="index"> Upload </b-button>
<input type="file" ref="file" style="display: none;"/>

and this in my script / methods:

methods: {
  selectFile() {
    this.$refs.file;
  }
}

Result: When I click the button nothing happend - but I get no error as well.

Thanks for your help !

2 Answers 2

0

Instead of using a button, you should use a <label> instead with the for attribute. You can then use CSS to style the label to look like a button.

<label for="file" class="btn btn-success"> Upload </label>
<input id="file" type="file" style="display: none;" />

Since you're using it in a v-for you will need to generate dynamic ID's for your input. For this you could either use a unique identifier if your items have one, or you could use the index.

<div v-for="(item, index) in items">
  <label :for="`file-${index}`" class="btn btn-success"> Upload </label>
  <input :id="`file-${index}`" type="file" style="display: none;"/>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

In Vue with BootstrapVue:

How code below works:

  1. Open file explorer on button (label) click;
  2. Select a file, continue;
  3. @onChange will detect new file:
<label>
  <button/> //this can be an icon, link,...
  <input @change="doSomething" type="file" ref="file" accept="image/gif, 
    image/jpeg, image/png" hidden/>
</label>
  1. Handle the file
doSomething(e: any) { 
  const file = e.target.files[0]
}

Question is a duplicate, my answer tho

3 Comments

It's fairly bad practice to place interactive content inside a <label>, and it also doesn't work unless the associated input is placed first, meaning the example you've written out doesn't work. At least when i tested on win10, Chrome.
This works in Vue2 without any problems. Can you tell me something more about the "bad practice"?
Placings interactive content inside a label is bad for accessibility, and general goes against the HTML spec. Here's the code i tried, which didn't work, codepen. The spec mentions that if no for attribute is used, then the first labelable element (button/label) is used. Which means in your example, clicking the label activates the button, not the input, since it's first. Also mentioned here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.