Home > database >  Bind B-Button with input file / BootstrapVue
Bind B-Button with input file / BootstrapVue

Time:09-30

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 !

CodePudding user response:

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>

CodePudding user response:

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

  • Related