【问题标题】:Check if v-model is empty?检查 v-model 是否为空?
【发布时间】:2026-01-30 20:10:01
【问题描述】:

如果用户没有输入任何内容,我想阻止。我试过这样但它不起作用:

 if(this.comment === ' '){
       return;
  }

这是我的全部方法:

 postComment: function(user_id,article_id) {
                if(this.comment === ' '){
                  return;
                }
                else{
                var article_comments = {
                  title: this.comment,
                  upovotes: this.article_comments.upovotes,
                  downvotes: this.article_comments.downvotes,
                  user_id : user_id,
                  article_id: article_id
                };

                  this.comments.push({
                      title: this.comment,
                      downvotes: 0,
                      upvotes: 0
                    })

                    this.$http.post('/blog/article/' + article_id + '/comment', article_comments).then(function(response){

                    },function(response){

                  });

                }
                this.comment = "";
              },

鉴于我有这个:

  <div class="col-md-11 col-sm-11 col-xs-11">
     <textarea  class="comment_input" placeholder="Join the discussion..." v-model="comment" @keyup.enter="postComment({{$current_user->id}},{{ $article->id}})"></textarea>
 </div>

【问题讨论】:

  • 您正在检查用户是否输入了空格。如果您想检查他们是否没有输入任何内容,它应该是if(this.comment == '') - 究竟什么是“不工作”?你得到什么错误?
  • if(this.comment == ''){ console.log('empty'); } else{ console.log('not empty');我知道它不是空的,即使它是
  • 可能是因为我在使用 keyup.enter??
  • 是的,也许您在按 Enter 时插入了一个新行。您应该使用@keyup.enter.prevent="postComment(...)" 阻止默认操作。此外,您应该在检查之前修剪输入以忽略空格:v-model.trim="comment"。如果还是不行,看看console.log(comment, comment.length);给你什么。
  • 我添加了 v-model.trim 和 @keyup.enter.prevent 但它再次不起作用,我得到这样的评论:comment" " , second " 进入另一行

标签: laravel laravel-5 laravel-5.2 vue.js


【解决方案1】:

首先,您正在检查' ',它不是空白文本而是空格。如果你想检查一个空白文本,它会是

if(this.comment === '')

if(this.comment.length == 0)

其次,你应该修剪输入前后的空白:

if(this.comment.trim() === '')

或者,从 Vue 2.0+ 开始,您可以直接在标记中使用 trim input modifier

<textarea v-model.trim="comment" ...>

最后但并非最不重要的一点是,您应该监听 keydown 而不是 keyup 事件,以便在您按下键时获得输入,而不是在键已经通过添加新队。既然你想自己处理这个事件,你应该阻止默认操作:

<textarea @keydown.enter.prevent="postComment()" ...>

【讨论】: