我输入了样式文件。它工作正常,但是选择文件后,我想显示所选的文件名而不是No files selected
。如何在Vue中做到这一点?
.fileContainer {
overflow: hidden;
position: relative;
background-color: #8181fe;
color: #fff;
padding: 6px 18px;
border-radius: 7px;
line-height: 21px;
}
form input, textarea {
background-color: #fff;
padding: 10px;
border: 1px solid #d9dadc;
border-radius: 7px;
font-size: 16px;
color: #393645;
resize: none;
}
.fileContainer [type=file] {
cursor: pointer;
display: block;
font-size: 13px;
filter: alpha(opacity=0);
min-height: 100%;
min-width: 100%;
opacity: 0;
position: absolute;
left: 0;
text-align: right;
top: -8px;
}
.file-info {
font-size: 13px;
color: #a9a7a9;
line-height: 53px;
padding-left: 10px;
}
<div id="contact-form" class="contact-form">
<form class="form">
<div class="section-file">
<label class="fileContainer">
Select files
<input type="file" class="file-upload" id="file" name="file" accept="jpg/image/jpeg/image/png">
</label>
<span class="file-info">No files selected</span>
</div>
</form>
</div>
答案 0 :(得分:1)
请注意,change
event的目标是关联的<input>
,并且所选文件在<input>.files
中指示,该文件的文件数具有length
属性。然后,我们可以将非零长度作为布尔值进行跟踪,以确定是否显示No files selected
:
files
数据属性以跟踪所选的files:data() {
return {
files: null
}
},
v-if
根据以上No files selected
有条件地渲染files
。在v-else
分支中,我们显示所选文件的列表:<span v-if="!files || !files.length">No files selected</span>
<ul v-else>
<li v-for="file in files" :key="file.name">{{file.name}}</li>
</ul>
change
中添加<input>
-event handler:<input @change="filesSelected">
methods
中定义处理程序方法:methods: {
fileSelected(e) {
this.files = e.target.files
}
}
new Vue({
el: '#contact-form',
data() {
return {
files: null
}
},
methods: {
fileSelected(e) {
this.files = e.target.files
}
}
})
.fileContainer {
overflow: hidden;
position: relative;
background-color: #8181fe;
color: #fff;
padding: 6px 18px;
border-radius: 7px;
line-height: 21px;
}
form input, textarea {
background-color: #fff;
padding: 10px;
border: 1px solid #d9dadc;
border-radius: 7px;
font-size: 16px;
color: #393645;
resize: none;
}
.fileContainer [type=file] {
cursor: pointer;
display: block;
font-size: 13px;
filter: alpha(opacity=0);
min-height: 100%;
min-width: 100%;
opacity: 0;
position: absolute;
left: 0;
text-align: right;
top: -8px;
}
.file-info {
font-size: 13px;
color: #a9a7a9;
line-height: 53px;
padding-left: 10px;
}
<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
<div id="contact-form" class="contact-form">
<form class="form">
<div class="section-file">
<label class="fileContainer">
Select files
<input type="file" class="file-upload" id="file" name="file" @change="fileSelected" multiple accept="image/jpg,image/jpeg,/image/png">
</label>
<span class="file-info" v-if="!files || !files.length">No files selected</span>
<ul v-else>
<li v-for="file in files" :key="file.name">{{file.name}}</li>
</ul>
</div>
</form>
</div>