从动态值创建vue.js v模型

时间:2019-03-06 11:02:34

标签: vue.js nuxt

我正在动态生成一些复选框。现在,我需要动态创建v模型。

<div class="form-group input-group">
   <label class="form-group-title">DIETARY PREFERENCES</label>
    <p>Please mark appropriate boxes if it applies to you and/or your family</p>
      <div class="check-group" v-for="v in alldietry" :key="v">
           <input type="checkbox" v-model="userinfo.{{#Here will be the value}}" value="" id="Vegetarian"> 
      <label for="Vegetarian">{{v.title}}</label>
        </div>
  </div>

进入v-model,我尝试v-model="userinfo.{{xyz}}"显示错误。

2 个答案:

答案 0 :(得分:1)

要将动态对象绑定到模型,您需要访问模型值和用于显示列表的数据集共享的键。

let vm = new Vue({
el: '#app',
  data: {
    userinfo: {
      0: '',
      1: ''
    }
  },
  computed: {
    alldietry() {
      return [
      	{
          id: 0,
          title: 'Title'
        },
        {
          id: 1,
          title: 'Title'
        }
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" class="form-group input-group">
  <label class="form-group-title">DIETARY PREFERENCES</label>
  <p>Please mark appropriate boxes if it applies to you and/or your family</p>
  <div class="check-group" v-for="(v, index) in alldietry" :key="index">
    <input type="checkbox" v-model="userinfo[v.id]" value="" :id="v.id"> 
    <label :for="v.id">{{v.title}}</label>
  </div>
  {{ userinfo }}
</div>

答案 1 :(得分:1)

You can't use {{ }} interpolation inside attributes.

The v-model value is a javascript expression, so instead of

v-model="userinfo.{{xyz}}"

you can just do

v-model="userinfo[xyz]"

as you would normally do in javascript when accessing an arbitrary property of an object.