从动态值创建vue.js v-model

问题描述 投票:1回答:2

我正在动态生成一些复选框。现在我需要创建v-model动态。

<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}}"它显示错误。

vue.js nuxt
2个回答
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
投票

你不能在属性中使用{{ }}插值。

v-model值是一个javascript表达式,所以代替

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

你可以这样做

v-model="userinfo[xyz]"

正如您在访问对象的任意属性时通常在javascript中所做的那样。

© www.soinside.com 2019 - 2024. All rights reserved.