使用v-for时设置初始v模型值

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

我有一个选择,我想填充计算数据,它工作正常:

   <select style="width: 175px">
       <option>None</option>
       <option v-for="label in labels">{{label.description}</option>
    </select>

    var vm = new Vue({
            el: '#div',
            data: {
            },
            computed: {
                labels: function () {
                //return labels based on some logic
                }
            }
        });

但是,我想将选定的值绑定到属性,所以我将我的代码更改为:

   <select style="width: 175px" v-model=selectedLabel">
       <option>None</option>
       <option v-for="label in labels">{{label.description}</option>
    </select>

    var vm = new Vue({
            el: '#div',
            data: {
              selectedLabel: ''
            },
            computed: {
                labels: function () {
                //return labels based on some logic
                }
            }
        });

然后我在选择中根本没有数据。这显然是因为我将selectedLabel设置为'',但我的选择中没有空选项。但我该如何解决这个问题呢?我不知道将要计算什么数据,所以我无法预定义selectedLabel。

javascript vue.js
1个回答
1
投票

只需将选择选项的默认值设置为'',如:

<div id="app">
  <select style="width: 175px" v-model="selectedLabel">
   <option value="">None</option>
   <option v-for="label in labels" :value="label.value">{{label.description}}</option>
  </select>
</div>

这将自动选择none选项。

看到这个fiddle

var vm = new Vue({
  el: '#app',
  data: {
    selectedLabel: ''
  },
  computed: {
    labels: function () {
      return [
        {description:'test', value: 'test'}, 
        {description: 'test1', value: 'test1'}
      ]
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <select style="width: 175px" v-model="selectedLabel">
   <option value="">None</option>
   <option v-for="label in labels" :value="label.value">{{label.description}}</option>
  </select>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.