2016-12-14 33 views
0

我正在嘗試使用Laravel 5.3和Vue.js進行一些簡單的表單驗證。Vue.js不設置數據

Laravel控制器:

public function test(\Illuminate\Http\Request $request) 
    { 
     $this->validate($request, [ 
      'name' => 'required', 
      'date' => 'required' 
     ]); 
... 
    } 

Vue的數據:

let app = new Vue({ 
     el: '#app', 

data: { 
     submitted: false, 
     errors: [], 
     post: { 
       name: '', 
       date: '', 
       }, 
}, 

Vue公司後:

Vue.http.post('url', post).then((response) => { 
    // form submission successful, reset post data and set submitted to true 
    app.post = { 
     name: '', 
     date: '', 
    }; 

    // clear previous form errors 
    app.$set('errors', ''); 

    app.submitted = true; 

}, (response) => { 
    // form submission failed, pass form errors to errors array 
    console.log(response.data.name); //"The Name field is required." 
    app.$set('errors', response.data); // TypeError 
}); 

我越來越

TypeError: can't assign to properties of (new String("errors")): not an object

app.$set('errors', response.data);

我在哪裏出錯了?

+0

你觸發'Vue.http.post'的方法如何? 'Vue.http'用於全局用途,有一個'this。$ http.post'指的是Vue實例,所以考慮正確的用例。這個承諾看起來有點奇怪,接受什麼第二個方法迴應呢? –

+0

@BelminBedak,'this。$ http.post'產生相同的結果。 – suncoastkid

+0

好的,這裏的承諾呢?可能有兩種情況:'.then()'承諾履行時,'.catch()'有問題。第二種方法有參數響應嗎? –

回答

3

檢查vm.$set(object, key, value),你要一個屬性添加到字符串「錯誤」使用response.data的關鍵。

正確的語法是app.$set(app, 'errors', response.data)app.errors = response.data應該工作得很好。

+0

啊!我最初在不需要對象的地方使用'this':'this。$ set('errors',response.data)'謝謝你的澄清。 – suncoastkid

+0

['this. $ set'和'Vue.set'](https://github.com/vuejs/vue/blob/dev/src/core/observer/index.js#L191)(它們是相同的東西)需要將目標對象作爲第一個參數傳遞。 –

+0

你是對的...看起來像是從v0.12' obj。$ set(key,value)'http://012.vuejs.org/guide/best-practices.html#Adding_and_Deleting_Properties – suncoastkid