2017-12-11 12 views
1

私はフォームと選択コンポーネントを持っています。 事実は単純です:私は2つの結合モデルが必要です。vue jsでコンポーネントをバインドする方法は?

親コンポーネント:

Vue.component('some-form', { 
     template: '#some-form', 
     data: function() { 
     return { 
      countryNameParent: '' 
     } 
     } 
    }); 

アイテムと子コンポーネント:

Vue.component('countries', { 
    template: '#countries', 
    data: function() { 
    return { 
     items: { 
     "0": { 
      "id": 3, 
      "name": "Afghanistan"   
     }, 
     "1": { 
      "id": 4, 
      "name": "Afghanistan2"   
     }, 
     "2": { 
      "id": 5, 
      "name": "Afghanistan3"   
     } 
     }, 
     countryName: '' 
    } 
    }, 
    props: ['countryNameParent'], 
    created: function() { 
    var that = this; 
    this.countryName = this.countryNameParent; 
    }, 

    methods: { 
    onChange: function (e) { 
     this.countryNameParent = this.countryName; 
    } 
    } 
}); 

私は上記のコンポーネントを組み込むことv-modelを使用しています。このような テンプレート:私の目標は、(実際のフォームがはるかに大きいです)、それをサーバに送信する親コンポーネントにデータを取得している

<template id="some-form"> 
    {{ countryNameParent }} 
    <countries v-model="countryNameParent"></countries> 
</template> 

<template id="countries"> 
    <label for=""> 
    <select name="name" @change="onChange" v-model="countryName" id=""> 
     <option value="0">Select the country!</option> 
     <option v-for="item in items" v-bind:value="item.name">{{ item.name }}</option> 
    </select> 
    </label> 
</template> 

、しかし私はcountryNameParentcountryNameの値を取得することはできません。また、親は空でない場合は後続のデータを設定する必要があります。ここで

あなたは(それのコメント部分を参照)、私はそれをいくつかの方法を実行しようとしてきたlinkを行きます。 私はので、私は解決策が近づいていると思いますが、私は、私も、私は同じ形のくぼみで、それを送信するためにBASE64などの画像を取得したモデルを実装しましたデータを正しく設定するために$emitを使用する必要があることを知っています!また

:私は、画像でサンプルを構築しましたreference。ここで

+1

あなただけの適切 'V-model'を実装する必要があります。あなたの[ペン更新](https://codepen.io/Kradek/pen/OzLdpK?editors=1010)です。 – Bert

+0

私はそれを感謝します!ありがとう! – Jarvis

答えて

2

v-modelをサポートするように更新あなたのcountriesコンポーネントです。

Vue.component('countries', { 
    template: ` 
    <label for=""> 
    <select v-model="countryName"> 
     <option value="0">Select the country!</option> 
     <option v-for="item in items" v-bind:value="item.name">{{ item.name }}</option> 
    </select> 
    </label> 
    `, 
    data: function() { 
    return { 
     items: { 
     "0": { 
      "id": 3, 
      "name": "Afghanistan"   
     }, 
     "1": { 
      "id": 4, 
      "name": "Afghanistan2"   
     }, 
     "2": { 
      "id": 5, 
      "name": "Afghanistan3"   
     } 
     }, 
    } 
    }, 
    props: ['value'], 
    computed:{ 
    countryName: { 
     get() { return this.value }, 
     set(v) { this.$emit("input", v) } 
    } 
    }, 
}); 

v-modelvalueプロパティを設定し、inputイベントを聴くためだけの糖です。したがって、コンポーネントをどのコンポーネントでもサポートするには、コンポーネントがvalueプロパティを受け入れ、inputイベントを送出する必要があります。どのプロパティとイベントを使用するかは設定可能です(文書番号here)。

+0

ありがとう! – Jarvis

関連する問題