我正在使用VueRouter创建单页应用程序,使用VeeValidate进行验证。我想添加一个方法来检查页面上有效输入的状态,以确定是否进展。
输入看起来像这样:
<input
type="text"
class="ze-input"
placeholder="Enter mobile number"
v-validate="'required'"
:class="{'input': true, 'is-danger': errors.has('mobile number') }"
name="mobile number"
>
我使用router-link
来推进路由器:
<router-link to="send_to_hospital" class="col-sm-12 navigation ze-button">
Next
</router-link>
如果在点击router-link
时如何验证页面,如果验证失败则如何停止进展?
我的路由配置文件:
import Vue from 'vue'
import Router from 'vue-router'
import HowCanWeHelpYou from '@/components/how_can_we_help_you'
import AboutSelf from '@/components/about_self'
import AppointmentInfo from '@/components/appointment_info'
import ContactUs from '@/components/contact_us'
import SendToHospital from '@/components/send_to_hospital'
import Confirmed from '@/components/confirmed'
import VeeValidate from 'vee-validate'
import vmodal from 'vue-js-modal'
Vue.use(VeeValidate)
Vue.use(vmodal)
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: '/',
component: HowCanWeHelpYou
},
{
path: '/about_self',
name: 'about_self',
component: AboutSelf
},
{
path: '/appointment_info',
name: 'appointment_info',
component: AppointmentInfo
},
{
path: '/contact_us',
name: 'contact_us',
component: ContactUs
},
{
path: '/send_to_hospital',
name: 'send_to_hospital',
component: SendToHospital
},
{
path: '/confirmed',
name: 'confirmed',
component: Confirmed
}
]
})
答案 0 :(得分:1)
Vue Router允许您在几个不同的地方设置Navigation Guards。这些防护是挂钩,您可以在路径更改时验证字段,然后在任何字段无效时阻止更改。
将beforeRouteLeave
守卫添加到包含字段的组件中可能最有意义:
beforeRouteLeave(to, from, next) {
// Tells VeeValidate to validate all the fields in the component's scope
this.$validator.validateAll();
if (!this.errors.any()) { // if there are no errors
next(); // go to the next route
}
// otherwise, next() doesn't get called and the route doesn't change
}