Javascript functions are not working properly in the vuejs

我的梦境 提交于 2019-12-13 04:08:44

问题


Below is my code. I would like to validate the form during submit. I prevented submit action untill all data is valid. Hence I have used "validata all()" method. If the form has null/invalid date, it should alert "not submitted".Else it should alert "submitted". My problem is that, when I clicked the submit button at first time, the alert displays as "submitted" instead of "not submitted" Result1. But when I clicked the same button for the second time or further it displays correctly as "not submitted" Result2. I don't know the reason, why it's not working in the first time.

<template>
           <div id="app">
            <h1>Add Items</h1>
            Product Name : 
            <input type="text" name="product" v-validate="'required|alpha_dash'" >
            <span style="color:red;">{{errors.first('product')}}</span>
            <br>
            Product Price : 
            <input type="number" name="price" v-validate="'required|min_value:100|max_value:500'">
            <span style="color:red;">{{errors.first('price')}}</span>
            <br>
            <button @click="submit">Save</button>
          </div>
        </template>

          <script>
          import Vue from 'vue'
          import VeeValidate from 'vee-validate'
          Vue.use(VeeValidate)

        export default {
          name: 'addEmpl',
          methods: {
           submit() {
              this.$validator.validateAll()
              if (!this.errors.any()) {
                alert('submitted')
              }else{
                 alert('not submitted')
              }
           }
          }
        }
          </script>

回答1:


Try .then(...) after validateAll() method:

this.$validator.validateAll().then((result) => {
  if(!result){
    alert('not submitted')
    return
  }
  alert('submitted')
}).catch(() => {
  // error check if needed
})

Also, there is an issue for a case alike here on Github page. You can have a look.



来源:https://stackoverflow.com/questions/50151874/javascript-functions-are-not-working-properly-in-the-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!