我在Laravel + Vue.js SPA(单页应用程序)中使用BootstrapVue和VeeValidate。当表单字段无效时,它将自动显示各个位置的错误。但是我需要一种方法,以便每当任何形式的输入无效时,我都可以在div
id
内的result
内显示一条消息(即“无效数据”) }。
我的form
组件具有以下形式:
Register.vue
JS部分具有:
<template>
<ValidationObserver ref="form" v-slot="{ passes }">
<div id="registration_form">
<div id="page_header" class="text-center" >Register</div>
<div id="result" v-html="result" class="result text-center"></div>
<b-form @submit.prevent="passes(onSubmit)" @reset="resetForm">
<ValidationProvider vid="name" rules="required|min:2" name="name" v-slot="{ valid, errors }">
<b-form-group
label="User Name:"
label-for="exampleInput1"
>
<b-form-input
type="text"
disable-leading-trailing-space
v-model="name"
:state="errors[0] ? false : (valid ? true : null)"
placeholder="Enter your name"
></b-form-input>
<b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>
</b-form-group>
</ValidationProvider>
<ValidationProvider vid="email" rules="required|email" name="Email" v-slot="{ valid, errors }">
<b-form-group
label="Email address:"
label-for="exampleInput1"
description="We'll never share your email with anyone else."
>
<b-form-input
type="email"
disable-leading-trailing-space
v-model="email"
:state="errors[0] ? false : (valid ? true : null)"
placeholder="Enter email"
></b-form-input>
<b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>
</b-form-group>
</ValidationProvider>
<b-button type="submit" variant="primary">Submit</b-button>
<b-button type="reset" variant="danger">Reset</b-button>
</b-form>
</div><!-- end of id registration_form-->
</ValidationObserver>
</template>
每当任何<script>
import { ValidationObserver, ValidationProvider } from "vee-validate";
export default {
name: "Register",
components: {
ValidationObserver,
ValidationProvider
},
data: () => ({
name: "",
email: "",
result:''
}),
methods: {
onSubmit() {
console.log("Form submitted yay!");
},
resetForm() {
this.name = "";
this.email = "";
requestAnimationFrame(() => {
this.$refs.form.reset();
});
}
}
};
</script>
输入处于无效状态时,我都想在form
中以div
id
显示消息“无效数据”。
是否有诸如result
之类的事件或完成该事件的其他任何方式?
编辑:
每当前端发生任何验证错误时,我也想将窗口滚动到顶部(beforeSubmit
)。该怎么做?
答案 0 :(得分:0)
从failed
插槽道具获得ValidationObserver
状态:
<ValidationObserver ref="form" v-slot="{ failed, passes }">
<div v-if="failed">Invalid Data</div>
<!-- rest of your fields -->
</ValidationObserver>