1

I'm trying to open a selection of files, but through passing prop to component (I need this for convenience). Is there a way to do this?

https://codepen.io/iliyazelenko/pen/RBejRV?editors=1010

Variant in code below does not suit me:

  <input type="file" ref="input" hidden>

  <button @click="() => { $refs.input.click() }">Choose file</button>

Why does it click but does not open file selection?

this.$refs.input.addEventListener('click', e => {
  console.log('clicked: ', e.target)
})
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

It will not work if it's not triggered from inside the click event.

What you can do is create a method inside your child component that can be called from the parent component within the event listener callback.

const compo = Vue.component("compo", {
  template: '<input type="file" ref="input" hidden>',
  mounted() {
    this.$refs.input.addEventListener('click', e => {
      console.log('clicked: ', e.target)
    })
  },
  methods: {
    open() {
      this.$refs.input.click()
    }
  }
})

new Vue({
  el: '#app',
  components: {
    compo
  },
  data() {
    return {
      propForComponent: false
    };
  },
  methods: {
    onClick() {
      this.$refs.compo.open()
    }
  }
})
<compo ref="compo"></compo>

<button @click="onClick">Choose file</button>

See this updated pen: https://codepen.io/WisdomSky/pen/GBYyGL?editors=1010

Julian Paolo Dayag
  • 3,562
  • 3
  • 20
  • 32