gpt4 book ai didi

javascript - 如果输入字段验证失败,则防止路由更改

转载 作者:太空宇宙 更新时间:2023-11-04 15:34:30 24 4
gpt4 key购买 nike

我正在使用 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
}
]
})

最佳答案

Vue Router 允许您设置 Navigation Guards在几个不同的地方。这些防护是钩子(Hook),您可以在路由更改时验证字段,然后在任何字段无效时阻止更改。

向包含这些字段的组件添加一个 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
}

关于javascript - 如果输入字段验证失败,则防止路由更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44508328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com