vantUI中的van-form使用 vue2版本

发布于:2024-08-08 ⋅ 阅读:(36) ⋅ 点赞:(0)

使用@submit="onSubmit"提交,然后button按钮native-type="submit"提交,单个form的时候没有问题,但是多个form组件多次点击的时候就容易出现混乱提交

<van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="用户名"
    label="用户名"
    placeholder="用户名"
    :rules="[{ required: true, message: '请填写用户名' }]"
  />
  <van-field
    v-model="password"
    type="password"
    name="密码"
    label="密码"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写密码' }]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">提交</van-button>
  </div>
</van-form>

优化使用@click方法点击,然后validate()进行校验***********************************

<van-form ref="ruleForm">
  <van-field
    v-model="submitForm.username"
    name="用户名"
    label="用户名"
    placeholder="用户名"
    :rules="rules.username"
  />
  <van-field
    v-model="submitForm.password"
    type="password"
    name="密码"
    label="密码"
    placeholder="密码"
    :rules="rules.password"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" @click="handleSubmit">提交</van-button>
  </div>
</van-form>

<script>
export default {
	data(){
		submitForm:{
			username:"",
			password:"",
		},
		rules:{
			username:[{ required: true, message: '请填写用户名' }],
			password:[{ required: true, message: '请填写密码' }]
		}
	},
	methods:{
		handleSubmit(){
			const _this = this;
			this.$refs.submitForm.
			?.validate()
			.then(() => {
	          console.log("验证成功");
	          //提交数据  _this.submitForm
	          console.log(_this.submitForm)
	        })
	        .catch(() => {
	          console.log("验证失败");
	        });
		}
	}

}
</script>




网站公告

今日签到

点亮在社区的每一天
去签到