首页 > 解决方案 > 如何在提交前检查 v-model 是否为空并显示错误

问题描述

我有输入标签、图像选择和发布按钮。如果用户没有输入任何内容,我需要阻止提交。我试过这样但它不起作用。任何人都知道如何防止这种情况

我正在使用 V 模型进行输入

     <select class="form-control" v-model="selected"  required>
         <option value="">SELECT A USER</option>
     <option v-for="user in users"  v-bind:value="user.id" >{{ user.first_name }}&nbsp;{{ user.last_name }}</option>
 </select>



<textarea id="post-box" class="post-box"   v-model="kudodescription" placeholder="What's on your mind" style="max-width:98%; min-width:98%; border:none; font-size: 16px;"  ></textarea>

<button  v-on:click="addKudoPost(authuser)" class="[ btn btn-primary ] pull-left" style="margin-top:0.8%;margin-right:1%;">Post Kudo</button>


<div class="col-md-6">



    <div  v-for="(kudo, index) in catkudo" class="class" v-bind:class="{ active: isActive == index }" >
        <div    @click="changeSelected(index)" >
            <img  style="width:40%"   v-bind:value="kudo.id" @click="select(kudo.id)"   v-model="kudocat"  :src="'/kudosuploads/badges/'+kudo.image" alt=""  >
        <p >{{ kudo.catname }}</p>
        </div>
    </div>



</div>

</div>

Vue方法如下

   // Add Kudo 

  addKudoPost: function(profile_id){


      if(this.kudodescription === null)
      {
            console.log("Error Occured");
      }else
      {
            var formkudodata = new FormData();

    formkudodata.append('kudodescription', this.kudodescription);

    formkudodata.append('kudouser', this.selected);

    formkudodata.append('kudoimage', this.clickimage);



    axios.post('/addNewsFeedKudoPost', formkudodata)
        .then(response=>{

        console.log(this);
        if(response.status===200){

          this.kudodescription = "";


        axios.get('/getNewsFeedPosts')
   .then(response => {
      this.posts = response.data.posts; 
      this.birthdays = response.data.birthdays; 

      console.log(response.data.posts);

      this.newsfeedPostImages();

  })
   .catch(function (error) {
      console.log(error);
  });

       }
   })
    .catch(function (error) {
       if(error.response.status == 422) {
           this.errors = error.response.errors
       }
    });

      }



},

如果用户没有输入内容如何防止表单提交并显示错误

标签: laravelvue.js

解决方案


可以是任何一个。v-on:submit.prevent="onSubmit" v-on:click.prevent="select(kudo.id)"

我不知道您在哪里提交,但如果您想了解更多信息,请查看此活动。


推荐阅读