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

标签 javascript validation vue.js vuejs2 vue-router

我正在使用 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/

相关文章:

javascript - HTML,是否可以从 "required"属性更改验证消息位置?

javascript - VueJs动态按钮值

vue.js - 将 Vue 指令置于条件

javascript - JavaScript 构造函数的用例

forms - 如何重置 ngFormModel 并丢失 Angular 2 Typescript 中的验证错误?

Javascript正则表达式-在两个字符之间逐个字符串分割字符串

jQuery 验证已停止与 Zurb 基金会合作

javascript - 在子组件中挂载父组件

javascript - 检测JS中的双Ctrl键

javascript - 使用D3.js单线图显示相同日期但不同温度