Vue表单的整体处理
在前端的处理中,表单的处理永远是占高比例的。在BOM+DOM+js的时候是这样,在Vue的时候也是这样。Vue的表单处理做了特别的优化,如值绑定、数据验证、错误提示、修饰符等。
表单组件的示例:
<script setup lang="ts">
import {ref} from "vue"
import axios from "axios"
const name=ref("");
const gender=ref("");
const birthDate=ref("");
const phone=ref("");
const applyReason=ref("");
const scopes=ref([]);
const luckyNumber=ref(1);
function submitForm(){
axios({
method:"post",
url:"",
params:{
name:name.value,
gender:gender.value,
birthDate:birthDate.value,
phone:phone.value,
applyReason:applyReason.value,
scopes:scopes.value,
lunckyNumber:luckyNumber.value
}
}).then((res)=>{
console.log(res);
});
}
function resetForm(){
name.value="";
gender.value="";
birthDate.value="";
phone.value="";
applyReason.value="";
scopes.value=[];
luckyNumber.value=1;
}
</script>
<template>
<form>
<div>
<div>
姓名:
<input v-model="name" id="name" placeholder="input your name"/>
</div>
<div>
性别:
<input type="radio" value="male" id="male" v-model="gender"/>
<lable for="male">男</lable>
<input type="radio" value="female" id="female" v-model="gender"/>
<lable for="female">女</lable>
</div>
<div>
出生日期:
<input type="date" id="birthDate" v-model="birthDate"/>
</div>
<div>
手机号码:
<input type="text" v-model="phone"/>
</div>
<div>
申请理由:
<textarea v-model="applyReason" placeholder="add reason here"></textarea>
</div>
<div>
涉猎范围:
<input type="checkbox" id="reading" value="reading" v-model="scopes"/>
<lable for="reading">阅读</lable>
<input type="checkbox" id="sports" value="sports" v-model="scopes"/>
<lable for="sports">运行</lable>
<input type="checkbox" id="dreaming" value="dreaming" v-model="scopes"/>
<lable for="dreaming">冥想</lable>
<input type="checkbox" id="playing" value="playing" v-model="scopes"/>
<lable for="playing">操作</lable>
</div>
<div>
幸运数字:
<select name="select" v-model="luckyNumber">
<option selected>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>
</div>
<div>
<button type="button" @click="submitForm">提交</button>
<button type="button" @click="resetForm">重置</button>
</div>
</div>
</form>
</template>
<style>
</style>
v-model在Vue中有三种修饰符:
v-model.lazy :由原来的input事件之后更新v-model的值改为change事件之后更新v-model的值,这对复合组件和计算属性有很大的作用
v-model.number :用户输入的内容会被自动转换为数字,输入框有type="number"时会自动启用
v-model.trim :用户的输入内容会自动去除两端的空格