我正在尝试使用这个插件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>它可以工作,但答案仅在保存时有效。加载时不确定该怎么做?例如,我从服务器获得的IpAddress是20.153.187.10,那么我如何选择合适的选项呢?
我不确定为什么作者忽略了这一点,因为它是如此基本的东西。
有没有更多的方法可以让它在保存和加载的同时也能正常工作?
发布于 2017-11-15 19:03:06
您将需要使用getOptoinLabel,并确保您使用的是最新版本的vue-select,因为我不确定哪个版本添加了该属性。因此,在引用您的example.You时,会将以下内容添加到代码中:
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;
}
}
}并在组件实例上添加属性:get-option-label="getLabel"
<v-select :get-option-label="getLabel" v-model="selected" label="first_name" :options="options"></v-select>
请注意,在默认情况下,上面的函数将参数val作为您传递的选项,即在本例中为v-model。因此,在您的情况下,它将是ip地址,然后您需要做的就是以您喜欢的方式过滤您的选项并返回名称。
https://stackoverflow.com/questions/47304650
复制相似问题