简体   繁体   中英

vue-select select the option based on ipaddress

I am trying to use this plugin https://github.com/sagalbot/vue-select

The issue with this is v-model gives the entire object unlike native select which is really a pain.

It is confirmed that the plugin does not support the option as outlined here https://github.com/sagalbot/vue-select/issues/122

The author suggests to use computed property for it. Here is the demo: http://jsbin.com/wedalog/8/edit?html,js,output

Here is the code:

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
    }   
  }
});

and here is how it used in html:

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

It works but the answer is only valid while saving. Not sure what to do when loading? For example the IpAddress which I get from the server is 20.153.187.10 How would I then the appropriate option?

I am not sure why the author ignored this for something as basic as this.

Is there any more hack to make it work which would work for saving as well as loading?

You will need to use getOptoinLabel and make sure you're using latest vue-select cause i'm not sure on which version that prop was added. So in reference to your example.You will add this to your code:

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;
     }
   }
}

And on the component instance add the prop :get-option-label="getLabel"

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

Note that the above function by default will have the argument val as the option you passed ie in this case the v-model. So in your case it will be the ip address and all you need to do is then filter through your options the way you like and return the name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM