2017-12-28 22 views
0

私はVueJs2を使用しています。 コンポーネントAは、2つのコンポーネントBとCで構成され、送信ボタンも含まれています。 各子コンポーネントには入力要素があります。 Aの送信ボタンをクリックすると、BとCからの入力を取得し、投稿要求を で送信する必要があります。Vuejs2の複数の子コンポーネントから入力を取得する方法は?

"成分A"

var A = { 
    components: { 
     'B', 
     'C', 
    }, 
    template: `<input type="button" value="submit" id="submit" v-on:click="submitMethod" />`, 
    methods: { 
     submitMethod: function() { 

     } 
    } 
} 

"B成分"

var B = { 
    template: `<input type="text" id="fname" v-model="fname" />`, 
    data: { 
     fname: '' 
    } 
} 

"C成分"

var C = { 
    template: `<input type="text" id="lname" v-model="lname" />`, 
    data: { 
     lname: '' 
    } 
} 

どのように私は阿智かもしれませんイブこれ?

答えて

0

私はあなたの懸念を理解しています。これらの質問は、Vueコミュニティではあまりよく答えられていません。あなたがReactから来ているなら、もちろん、いくつかの学習曲線がありますが、あなたはすべてのベストプラクティスを最初に知ることができます。

この場合、Vue、私のコンポーネントAには、BCの両方の入力に対して状態(データ)があります。私のテンプレートでは、こういうことをしています。

これで、すべてのデータがトップレベル(コンテナ)コンポーネントに格納されました。これにより、コンポーネントのほとんどはステートレスで再利用可能になります。私はこれが少し冗長だと理解していますが、それはそれが価値があると思います。

0

イベントドリブンアプローチを使用できます。これはchild to parentのデータを渡すよりエレガントな方法になります。ここから取ら

Vue.component('child', { 
 
    template: '#child', 
 
    
 
    //The child has a prop named 'value'. v-model will automatically bind to this prop 
 
    props: ['value'], 
 
    data: function() { 
 
    return { 
 
     internalValue: '' 
 
    } 
 
    }, 
 
    watch: { 
 
    'internalValue': function() { 
 
     // When the internal value changes, we $emit an event. Because this event is 
 
     // named 'input', v-model will automatically update the parent value 
 
     this.$emit('input', this.internalValue); 
 
    } 
 
    }, 
 
    created: function() { 
 
    // We initially sync the internalValue with the value passed in by the parent 
 
    this.internalValue = this.value; 
 
    } 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    inputs: {  
 
     value1: 'hello1', 
 
     value2: 'hello2' 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script> 
 

 
<div id="app"> 
 
    <p>Parent value: {{inputs}}</p> 
 
    <child v-model="inputs.value1"></child> 
 
    <child v-model="inputs.value2"></child> 
 
</div> 
 

 
<template id="child"> 
 
    <input type="text" v-model="internalValue"> 
 
</template>

参照:vuejs update parent data from child component 著者:

関連する問題