检查v-model是否为空?

Non*_*one 3 laravel vue.js laravel-5

我想防止用户未输入任何内容。我尝试过这样但它不起作用:

 if(this.comment === ' '){
       return;
  }
Run Code Online (Sandbox Code Playgroud)

这是我的整个方法:

 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 = "";
              },
Run Code Online (Sandbox Code Playgroud)

鉴于我有这个:

  <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>
Run Code Online (Sandbox Code Playgroud)

Qua*_*unk 5

首先,您要检查' ',它不是空白文本,而是空格。如果你想检查空白文本,那就是

if(this.comment === '')
Run Code Online (Sandbox Code Playgroud)

或者

if(this.comment.length == 0)
Run Code Online (Sandbox Code Playgroud)

其次,您应该修剪输入前后的空格:

if(this.comment.trim() === '')
Run Code Online (Sandbox Code Playgroud)

或者,从 Vue 2.0+ 开始,您可以直接在标记中使用修剪输入修饰符:

<textarea v-model.trim="comment" ...>
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的一点是,您应该监听而keydown不是keyup事件,以便您在按下按键时获得输入,而不是在按键已经通过添加新行修改输入之后获得输入。由于您想自己处理此事件,因此应该阻止默认操作:

<textarea @keydown.enter.prevent="postComment()" ...>
Run Code Online (Sandbox Code Playgroud)