我将以下模板用于自定义vue文件输入组件。
不幸的是, value:File 属性不起作用。
浏览和 change 事件似乎有效,但是 value 道具从不更改。
btw:我将tailwindcss用于样式。
以下是链接:https://codesandbox.io/s/file-upload-2-ekkmh
<template>
<div>
<label v-if="label" class="form-label">{{ label }}:</label>
<div class="p-2 leading-normal block w-full border text-gray-700 bg-white font-sans rounded text-left appearance-none relative outline-none p-0" :class="{ error: errors.length }">
<input ref="file" type="file" :accept="accept" class="hidden" @change="change" />
<div v-if="!value" class="p-2">
<button
type="button"
class="px-4 py-1 bg-gray-700 hover:bg-gray-800 rounded-sm text-xs font-medium text-white"
@click="browse"
>Browse</button>
</div>
<div v-else class="flex items-center justify-between p-2">
<div class="flex-1 pr-1">
{{ value.name }}
<span class="text-gray-700 text-xs">({{ filesize(value.size) }})</span>
</div>
<button
type="button"
class="px-4 py-1 bg-grey-700 hover:bg-gray-800 rounded-sm text-xs font-medium text-white"
@click="remove"
>Remove</button>
</div>
</div>
<div v-if="errors.length" class="form-error">{{ errors[0] }}</div>
</div>
</template>
<script>
export default {
props: {
value: File,
label: String,
accept: String,
errors: {
type: Array,
default: () => []
}
},
watch: {
value(value) {
console.log(value);
if (!value) {
this.$refs.file.value = "";
}
}
},
methods: {
filesize(size) {
var i = Math.floor(Math.log(size) / Math.log(1024));
return (
(size / Math.pow(1024, i)).toFixed(2) * 1 +
" " +
["B", "kB", "MB", "GB", "TB"][i]
);
},
browse() {
this.$refs.file.click();
console.log("click");
},
change(e) {
this.$emit("input", e.target.files[0]);
console.log('change');
},
remove() {
this.$emit("input", null);
}
}
};
</script>