2016-10-27 4 views
0

ajaxからerror-formコンポーネントにエラーを渡すにはどうすればよいですか?エラーフォームコンポーネントにエラーを渡しますか?

FormLink.vueコンポーネント:

<template> 

    <error-form></error-form> 

    <form class="form-horizontal"> 
    . 
    . 
    </form> 
</template> 

<script> 
    export default { 

     methods: { 
      addLink: function (event) { 
       event.preventDefault(); 
       this.$http.post('/user/link', {name: this.linkName, key: this.linkValue}).then(response => { 
        this.users.links.push(response.json()); 
        this.linkName = ''; 
        this.linkValue = ''; 
       }).error(function(errors) { 
        // how to pass errors data to <error-form> component? 
       }); 
      }, 
     } 
    } 
</script> 

ErrorForm.vueコンポーネント

<template> 
    <div class="alert alert-danger"> 
     <strong>Errors!</strong><br><br> 
     <ul> 
      <li></li> 
     </ul> 
    </div> 
</template> 

<script> 
    export default { 

     ready() { 
      console.log('Error Component ready.'); 
     }, 

     data: function() { 
      return { 

      } 
     }, 
    } 
</script> 
App.js

Vue.component('form-link', require('./components/Profile/FormLink.vue')); 
Vue.component('error-form', require('./components/Global/ErrorForm.vue')); 

答えて

1

は小道具を使用してデータを渡します。

FormLinkコンポーネント:

<template> 
    <error-form :errors="errors"></error-form> 
</template> 

<script> 
    EXPORT default { 

     data() { 
      return { 
      errors: [] 
      } 
     }, 

     methods: { 
      addLink: function (event) { 
       event.preventDefault(); 
       this.$http.post('/user/link', {name: this.linkName, key: this.linkValue}).then(response => { 
        this.users.links.push(response.json()); 
        this.linkName = ''; 
        this.linkValue = ''; 
       }).error(function(errors) { 

        this.errors = errors; 

       }); 
      }, 
     } 
    } 
</script> 

ErrorFormコンポーネント:

<template> 
    <div class="alert alert-danger"> 
     <strong>Errors!</strong><br><br> 
     <ul> 
      <li v-for="error in errors">{{ error }}</li> 
     </ul> 
    </div> 
</template> 

<script> 
    EXPORT default { 

     props: { 
     errors: Array 
     }, 

     ready() { 
      console.log('Error Component ready.'); 
     }, 

     data: function() { 
      return { 

      } 
     }, 
    } 
</script> 
+0

ありがとうございます。多くのコンポーネントで 'エラー:[]'がなくても、それをきれいに保つ方法がありますか? –

+0

@Ill-Be-Back親コンポーネントと子コンポーネントの両方にないことを意味しますか?あなたはそうしない。ネストされたコンポーネントを使用することは、懸念を避けることです。ここでは、親に 'addLink'を行い、これに関連していないajaxエラーを処理していると感じるので、子コンポーネントを作成し、エラーを渡して、親はエラーの処理について何もしません。 ( 'errors'の名前は両方のコンポーネントで同じである必要はないことに注意してください)親が一度に扱うには大きすぎない場合でも、子を親にインライン展開できますが、あなたは子供を再利用するつもりです。 –

関連する問題