2017-06-06 103 views
0

我有形式create.vue這樣的:處理表單驗證錯誤5.4 + vueJS

<template> 
    <div> 
     <div v-if="message" class="alert alert-success"> 
      {{ message }} 
     </div> 

     <form @submit.prevent="store" action="/user" method="post"> 
      <div :class="['form-group', errors.name ? 'has-error' : '']"> 
      <!--<div class="form-group">--> 
      <label>Full name</label> 
       <input v-model="state.name" type="text" class="form-control"> 
       <span v-if="errors.name" class="label label-danger">{{ errors.name[0] }}</span> 
       <!--<span class="label label-danger">{{ errors(errors.name) }}</span>--> 
      </div> 

      <div :class="['form-group', errors.email ? 'has-error' : '']"> 
      <!--<div class="form-group">--> 
       <label>Email</label> 
       <input v-model="state.email" type="email" class="form-control"> 
       <span v-if="errors.email" class="label label-danger">{{ errors.email[0] }}</span> 
       <!--<span class="label label-danger">{{ errors(errors.email) }}</span>--> 
      </div> 

      <div class="form-group"> 
       <button class="btn btn-primary">Submit</button> 
       <!--<router-link :to="{ name: 'userIndex' }">Back to index</router-link>--> 
      </div> 
     </form> 
    </div> 
</template> 

<script> 
export default { 
    data() { 
     return { 
      errors: [], 
      user: [], 
      state: { 
       name: '', 
       email: '' 
      } 
     } 
    }, 

    methods: { 
     store(e) { 
      axios.post(e.target.action, this.state).then(response => { 
       this.errors = []; 

       this.state = { 
        name: '', 
        email: '' 
       } 

       this.message = 'User has been created.'; 
      }).catch(error => { 
       if (! _.isEmpty(error.response)) { 
        if (error.response.status = 422) { 
         this.errors = error.response.data; 
        } 
       } 
      }); 
     } 
    } 
} 
</script> 

而且我的控制器: UserCOntroller.php

public function store(Request $request) 
    { 
     $this->validate($request, [ 
      'name' => 'required|string|max:50', 
      'email' => 'required|email|unique:users,email', 
     ]); 

     $user = User::create([ 
      'name'  => $request->name, 
      'email' => $request->email, 
      'password' => bcrypt(str_random()), 
     ]); 

     return response()->json($user); 
    } 

當我鍵入類似的東西是什麼曾經存在(唯一),我在控制檯響應中獲取錯誤文本,但不像往常一樣在窗體中顯示。我在控制檯中出現如下錯誤:

{"email":["The email has already been taken."]} 

如何在窗體中顯示? 我的腳本有什麼問題?

有幫助嗎?謝謝你..

+0

@Demonyowh,你是什麼意思?在JS 腳本錯誤下面VUE標籤模板 –

回答

1

嗨我試圖複製您的腳本在我的本地。雖然在我身上運作。你可以嘗試在catch中調試對象錯誤。發送示例結果:)

if (error.response.status = 422) { 
    this.errors = error.response.data; 
    console.log(this.errors);        
} 
+0

我得到響應 {電子郵件:「電子郵件已經採取」]} 和狀態 422無法處理的實體 –

+0

嗨請看看這個小提琴。 https://jsfiddle.net/khenxi/ev8wvg8p/ 如果'this.errors'確實包含正確的輸出,那麼它應該顯示 – Kzy