2017-03-29 67 views
0

假設我試圖製作一個簡單的問卷,用戶回答問題列表。組件範圍中的雙向綁定

new Vue(
{ 
    el: "#app", 
    data: 
    { 
     questions: 
     [ 
      { 
       id: 1, 
       name: "What is your favorite color?", 
       selectedId: 2, 
       choices: 
       [ 
        { id: 1, name: "red" }, 
        { id: 2, name: "green" }, 
        { id: 3, name: "blue" }, 
       ] 
      }, 
      ... 
     ] 
    } 
}); 

我該如何着手製作一個雙向綁定的問題組件。也就是說,如果用戶將他們喜歡的顏色從綠色交換到紅色,通過單擊相應的輸入,selectedId將自動更新。我不清楚v-模型如何在組件內工作。它只能訪問組件數據嗎?另外,我不明白道具/數據之間的區別。

+0

這難道不是一樣的http://stackoverflow.com/questions/43079230/vuetwo數據綁定與嵌套組件? –

+0

該域名是,但我不喜歡,我建議我自己的組件開始,因爲提供的答案是基於它。我想知道組件本身是否有更好的結構。另外,其他答案讓我更加困惑。文檔說使用v-model對輸入進行雙向綁定。但答覆是建議事件。如果我要使用事件,我不能簡單地使用JQuery或類似的東西嗎? –

回答

0

有很多,你可以處理這個方法,這是我的嘗試:

let id = 0; 
 

 
Vue.component('question', { 
 
    template: '#question', 
 
    props: ['question'], 
 
    data() { 
 
    return { 
 
     radioGroup: `question-${id++}`, 
 
    }; 
 
    }, 
 
    methods: { 
 
    onChange(choice) { 
 
     this.question.selectedId = choice.id; 
 
    }, 
 
    
 
    isChoiceSelected(choice) { 
 
     return this.question.selectedId === choice.id; 
 
    }, 
 
    }, 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    questions: [ 
 
     { 
 
     title: 'What is your favorite color?', 
 
     selectedId: null, 
 
     choices: [ 
 
      { id: 1, text: 'Red' }, 
 
      { id: 2, text: 'Green' }, 
 
      { id: 3, text: 'Blue' }, 
 
     ], 
 
     }, 
 
     { 
 
     title: 'What is your favorite food?', 
 
     selectedId: null, 
 
     choices: [ 
 
      { id: 1, text: 'Beans' }, 
 
      { id: 2, text: 'Pizza' }, 
 
      { id: 3, text: 'Something else' }, 
 
     ], 
 
     }, 
 
    ], 
 
    }, 
 
});
.question { 
 
    margin: 20px 0; 
 
}
<script src="https://rawgit.com/yyx990803/vue/master/dist/vue.js"></script> 
 

 
<div id="app"> 
 
    <question v-for="question of questions" :question="question"></question> 
 
</div> 
 

 
<template id="question"> 
 
    <div class="question"> 
 
    <div>{{ question.title }}</div> 
 
    <div v-for="choice of question.choices"> 
 
     <input type="radio" :name="radioGroup" :checked="isChoiceSelected(choice)" @change="onChange(choice)"> {{ choice.text }} 
 
    </div> 
 
    <div>selectedId: {{ question.selectedId }}</div> 
 
    </div> 
 
</template>