vue-select选择基于ipaddress的选项

时间:2017-11-15 10:13:56

标签: javascript vue.js vuejs2

我正在尝试使用此插件https://github.com/sagalbot/vue-select

这个问题是v-model给出了与本机选择不同的整个对象,这真是一种痛苦。

确认该插件不支持此处列出的选项https://github.com/sagalbot/vue-select/issues/122

作者建议使用计算属性。以下是演示:http://jsbin.com/wedalog/8/edit?html,js,output

以下是代码:

Vue.component('v-select', VueSelect.VueSelect);

new Vue({
  el: '#app',
  data: {
    selected: null,
    options: [
    {
      "id": 1,
      "first_name": "Timothy Chavez",
      "ip_address": "20.153.187.10"
    },
    {
      "id": 2,
      "first_name": "Harold Armstrong",
      "ip_address": "55.156.218.75"
    }, 
    {
      "id": 3,
      "first_name": "Randy Black",
      "ip_address": "79.135.200.161"
    }, 
    {
      "id": 4,
      "first_name": "Joshua Phillips",
      "ip_address": "146.153.135.116"
    }
    ]
  },
  computed: { 
    selectedIp() {
        return this.selected ? this.selected['ip_address'] : null
    }   
  }
});

以及它在html中的使用方式:

<v-select v-model="selected" label="first_name" :options="options"></v-select>

它有效,但答案仅在保存时有效。不知道加载时该怎么办?例如,我从服务器获取的IpAddress20.153.187.10我如何选择合适的选项?

我不确定为什么作者忽略了这个基本的东西。

是否有更多的黑客使其工作,这将有助于保存和加载?

1 个答案:

答案 0 :(得分:0)

您需要使用getOptoinLabel并确保使用最新的vue-select原因我不确定添加了prop的版本。所以参考你的例子。你将把它添加到你的代码中:

methods: {
   getLabel: function(val){
     if(typeof val === 'object'){
         return val.first_name;
     }else {
     return this.options.filter(function(option){
            return option.ip_address === val;
        })[0].first_name;
     }
   }
}

在组件实例上添加prop :get-option-label="getLabel"

<v-select :get-option-label="getLabel" v-model="selected" label="first_name" :options="options"></v-select>

请注意,默认情况下,上述函数将使用参数val作为您传递的选项,即在本例中为v-model。因此,在您的情况下,它将是IP地址,您需要做的就是按照您喜欢的方式过滤您的选项并返回名称。