Javascript v-model 不支持 input type="file"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41803012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:38:53  来源:igfitidea点击:

v-model doesn't support input type="file"

javascriptvue.jsvuejs2

提问by rap-2-h

I can not use v-modelwith file input, Vue says I must use v-on:change. Ok so I can use v-on:change, but how can I bind the "content" of the input file to a dataproperty?

我不能使用v-model文件输入,Vue 说我必须使用v-on:change. 好的,我可以使用v-on:change,但是如何将输入文件的“内容”绑定到data属性?

Let's say I want to bind it in a component to this.file:

假设我想将它绑定到一个组件中this.file

export default {
  data() {
    file: null
  },
  // ...
}

Here is the HTML part:

这是 HTML 部分:

<input id="image" v-on:change="???" type="file">
<!--                           ^- don't know how to bind without v-model -->

How should I do the binding?

我该怎么做绑定?

回答by Arun Ghosh

In the onchangeevent you should pass the event object to a function and handle:

onchange事件中,你应该通过事件对象的功能和处理:

onFileChange(e) {
  var files = e.target.files || e.dataTransfer.files;
  if (!files.length)
    return;
  this.createImage(files[0]);
},

For more information refer https://codepen.io/Atinux/pen/qOvawK/

有关更多信息,请参阅https://codepen.io/Atinux/pen/qOvawK/

回答by Linus Borg

Using v-modelwith a file input makes no sense, because you can't set a value on a file input - so what should a two-way binding do here?

v-model与文件输入一起使用没有意义,因为您无法在文件输入上设置值 - 那么双向绑定在这里应该做什么?

Just use v-on:change

只需使用 v-on:change