只读表单输入
在表单输入上使用 v-model 会创建双向绑定,这意味着如果 Vue 数据实例发生变化,输入值属性也会发生变化。
对于只读表单输入,如<input type="file">
,值属性无法从 Vue 数据实例更改,因此我们不能使用 v-model。
对于只读表单输入,如 <input type="file">
,我们需要使用 @change 来调用更新 Vue 数据实例的方法:
示例
App.vue:
<template>
<h1>输入类型文件</h1>
<form @submit.prevent="registerAnswer">
<label>选择文件:
<input @change="updateVal" type="file">
</label>
<button type="submit">提交</button>
</form>
<div>
<h3>已提交答案:</h3>
<p id="pAnswer">{{ inpValSubmitted }></p>
</div>
</template>
<script>
export default {
data() {
return {
fileInp: null,
inpValSubmitted: '尚未提交'
}
},
methods: {
registerAnswer() {
if(this.fileInp) {
this.inpValSubmitted = this.fileInp;
}
},
updateVal(e) {
this.fileInp = e.target.value;
}
}
}
</script>
<style scoped>
div {
border: dashed black 1px;
border-radius: 10px;
padding: 0 20px 20px 20px;
margin-top: 20px;
display: inline-block;
}
button {
margin: 10px;
display: block;
}
#pAnswer {
background-color: lightgreen;
padding: 5px;
}
</style>
信息:在上面的例子中,提交的文件名前面有一个文件路径 C:\fakepath\。这是为了防止恶意软件猜测用户的文件结构。
总结
本文介绍了Vue只读表单Form输入的使用,如有问题欢迎私信和评论