From 169f8b14056cebc672750f458f6ac9525535525c Mon Sep 17 00:00:00 2001 From: Troy Morehouse Date: Thu, 22 Jun 2017 20:51:39 -0300 Subject: [PATCH] [form-file] reset() method for clearing file value (#535) * [form-file] add reset() method * [form-file] documentation update --- docs/components/form-file/README.md | 27 +++++++++++++++++++++++++++ lib/components/form-file.vue | 15 +++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/docs/components/form-file/README.md b/docs/components/form-file/README.md index 4e04b571ec3..88e6b72e4e4 100755 --- a/docs/components/form-file/README.md +++ b/docs/components/form-file/README.md @@ -39,4 +39,31 @@ Also it is advised to use [:lang()](https://developer.mozilla.org/en-US/docs/Web } ``` +### Clearing the file selection +Because of limitations in the value binding with `` elements, `v-model` for `b-form-file`is +unidirectional, and cannot be used to set or clear the file(s) selection. To get around this +limitation `b-form-file` provides a `reset()` method that can be called to clear the file input. + +To take advantage of the `reset()` method, you will need to obtain a reference to the `b-form-file` component: + +```html +
+ + Reset +
+``` + +```js +window.app = new Vue({ + el: '#app', + data: { + file: null + }, + methods: { + clearFiles() { + this.$refs.fileinput.reset(); + } + } +}); +``` diff --git a/lib/components/form-file.vue b/lib/components/form-file.vue index 0fb1dd9a02a..b8c6f7a3f32 100755 --- a/lib/components/form-file.vue +++ b/lib/components/form-file.vue @@ -128,6 +128,21 @@ } }, methods: { + reset() { + try { + // Wrapped in try in case IE < 11 craps out + this.$refs.input.value = ''; + } catch (e) { + } + + // IE < 11 doesn't support setting input.value to '' or null + // So we use this little extra hack to reset the value, just in case + // This also appears to work on modern browsers as well. + this.$refs.input.type = ''; + this.$refs.input.type = 'file'; + + this.selectedFile = this.multiple ? [] : null; + }, onFileChange(e) { // Always emit original event this.$emit('change', e);