组件范围内的双向绑定

时间:2017-03-29 22:48:36

标签: vue.js

假设我正在尝试制作一份简单的调查问卷,用户可以回答一系列问题。

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-model在组件中的工作原理。它是否只能访问组件数据?另外,我不明白道具/数据之间的区别。

1 个答案:

答案 0 :(得分: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>