带有选择、v-for 和 v-model 的 Vue 预选值 [英] Vue preselect value with select, v-for, and v-model

查看:28
本文介绍了带有选择、v-for 和 v-model 的 Vue 预选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 selectv-model 一起使用,并且有带有 v-for 和 object 作为值的选项.选项是一些由 id 标识的元素.如何根据自定义相等性(在本例中为相等 id 字段)预选选项?我正在从 ng-options 中寻找类似于 angularjs 的 track by 的东西.

https://jsfiddle.net/79wsf1n4/5/

如何使输入预选为具有相同 id 的值?

模板:

<select v-model="selected"><option v-for="物品在库存中" :value="item" :key="item.id">{{ 项目名称 }}</选项></选择><p>{{ selected.id }}</p>

js:

var vm = new Vue({el: '#vue-instance',数据: {存货: [{名称:'MacBook Air',ID:1},{名称:'MacBook Pro',ID:2},{名称:'联想W530',ID:3},{名称:'宏碁 Aspire One',ID:4}],选择:{编号:2}}});

解决方案

您可以按照 Dharmendra 的回答添加 selected 属性.

然而,问题是您没有为所选属性分配有效的对象.Vue 将尝试在您的选项列表中查找相同的对象,它会通过对象相等性比较来完成此操作.

此时我不知道是否可以告诉 Vue 将初始选择基于属性,但是一个非常简单的解决方案是在创建的生命周期回调中根据 ID 自己分配所选属性:

var vm = new Vue({el: '#vue-instance',数据: {存货: [{名称:'MacBook Air',ID:1},{名称:'MacBook Pro',ID:2},{名称:'联想W530',ID:3},{名称:'宏碁 Aspire One',ID:4}],已选择:2},创建:函数(){this.selected = this.inventory.find(i => i.id === this.selected);}});

我也更新了您的Fiddle.

I'm using select with v-model and have options with v-for and object as a value. Options are some elements identified by id. How do I make option preselected based on custom equality (in this case by equal id field)? I'm looking for something similar to angularjs' track by from ng-options.

https://jsfiddle.net/79wsf1n4/5/

How to make the input preselected with the value with equal id?

template:

<div id="vue-instance">
  <select v-model="selected">
    <option v-for="item in inventory" :value="item" :key="item.id">
      {{ item.name }}
    </option>
  </select>
  <p>
    {{ selected.id }}
  </p>
</div>

js:

var vm = new Vue({
  el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', id: 1},
      {name: 'MacBook Pro', id: 2},
      {name: 'Lenovo W530', id: 3},
      {name: 'Acer Aspire One', id: 4}
    ],
    selected: {
        id: 2
    }
  }
});

解决方案

You could add the selected attribute as per Dharmendra's answer.

The issue however is that you're not assigning a valid object to your selected property. Vue will try to look for an identical object in your option list, it will do this by object equality comparison.

At this time I'm not aware whether it's possible to tell Vue to base the initial selection on an attribute, however a very simple solution is to assign the selected property based on the ID yourself in the created lifecycle callback:

var vm = new Vue({
  el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', id: 1},
      {name: 'MacBook Pro', id: 2},
      {name: 'Lenovo W530', id: 3},
      {name: 'Acer Aspire One', id: 4}
    ],
    selected: 2
  },
  created: function() {
        this.selected = this.inventory.find(i => i.id === this.selected);
  }
});

I've updated your Fiddle as well.

这篇关于带有选择、v-for 和 v-model 的 Vue 预选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆