大概想实现的是这种效果
文件名绑定到type为text的表单中,
上传文件按钮是在是太丑了。 但是网上有很多修改的方法,最常用的就是将其覆盖在自己重新写的另外一个按钮之下,然后设置透明,这样的话点击的实际还是之前的按钮,而样式我们可以随意修改。
> 但是我们在这里主要记录如何绑定文件名
大致的思路就是将text用v-model 绑定,然后监听当实际隐藏的文件改变时,将其文件名赋值给text
具体代码如下
html代码
<div class="file-upload-wrapper">
<input type="text" v-model="fileName" class="file-name" readonly placeholder="请选择文件" />
<input
type="file"
name="upload-file"
ref="upload-file"
id="upload-file"
class="upload-file"
@change="fileChange($event)"
/>
<button class="upload-btn">{{ fileName ? '重新选择' : '选择' }}</button>
</div>
css代码
.file-upload-wrapper {
position: relative;
cursor: pointer;
margin-bottom: 30px;
.file-name {
width: 328px;
height: 36px;
border: 1px solid $info-divider;
border-radius: 2px;
text-indent: 5px;
background: #f5f7fa;
}
.upload-file {
position: absolute;
width: 100px;
height: 36px;
left: 489px;
top: 0;
opacity: 0;
z-index: 99;
cursor: pointer;
}
.upload-btn {
position: relative;
width: 100px;
height: 36px;
line-height: 34px;
border: 1px solid $primary-color;
border-radius: 2px;
color: $text-highlight;
margin-left: -4px;
top: 0px;
}
js代码
fileChange(el) {
const file = el.target.files[0];
console.log(file);
this.fileName = file.name;
},