代码之家  ›  专栏  ›  技术社区  ›  Илья Зелень

为什么我不能通过prop触发输入文件?

  •  1
  • Илья Зелень  · 技术社区  · 7 年前

    我试图打开一个文件选择,但通过传递道具到组件(我需要这个方便)。有办法吗?

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

    下面代码中的变体不适合我:

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

    为什么单击但不打开文件选择?

    this.$refs.input.addEventListener('click', e => {
      console.log('clicked: ', e.target)
    })
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Julian Paolo Dayag    7 年前

    如果不是从单击事件内部触发,它将不起作用。

    您可以在子组件中创建一个方法,该方法可以从事件侦听器回调中的父组件调用。

    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>

    查看此更新笔: https://codepen.io/WisdomSky/pen/GBYyGL?editors=1010

    推荐文章