花了好几个小时,我试图在v-select中获取所选选项的ID,但它返回的对象不是ID。 有什么方法只能获取所选选项的ID(对象ID)?
我已经检查了文档站点: https://sagalbot.github.io/vue-select/docs/
我还检查了以下示例: https://codepen.io/collection/nrkgxV/
但是到目前为止,我还没有找到解决我的问题的具体方法。缺少什么或我做错了吗?
我的代码:
<template>
<div>
<v-select
v-model="selectedId"
:options="items"
label="name"
></v-select>
</div>
</template>
<script>
export default {
data () {
return {
items: [
{id: 1, name: "User 1", creator_id: 3},
{id: 2, name: "User 2", creator_id: 1},
{id: 4, name: "User 3", creator_id: 3},
],
selectedId: '',
...
}
}
答案 0 :(得分:2)
如何添加计算道具id
<script>
export default {
data () {
return {
items: [
{id: 1, name: "User 1", creator_id: 3},
{id: 2, name: "User 2", creator_id: 1},
{id: 4, name: "User 3", creator_id: 3},
],
selectedId: {}
}
},
computed: {
id: function () {
return (this.selectedId && this.selectedId.id)?this.selectedId.id:'';
}
}
}
</script>
答案 1 :(得分:1)
我花了很长时间才弄清楚,但显然您可以使用:reduce="item = item.id"
请参阅:https://vue-select.org/guide/values.html#getting-and-setting
一个真正的拯救者,因为“计算”方法无法解决我的情况
答案 2 :(得分:0)
除了使用v-model
之外,您还可以在select上监听事件:
Vue.component("v-select", VueSelect.VueSelect);
new Vue({
el: "#app",
data () {
return {
items: [
{id: 1, name: "User 1", creator_id: 3},
{id: 2, name: "User 2", creator_id: 1},
{id: 4, name: "User 3", creator_id: 3},
],
selectedId: ''
}
},
methods: {
selectId(e) {
this.selectedId = e.id
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-select/2.5.1/vue-select.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<v-select
@input="selectId($event)"
:options="items"
label="name">
</v-select>
<p>Selected ID: {{ selectedId }}</p>
</div>
答案 3 :(得分:0)
在 v-select 中添加这些属性
item-value="id" item-text="name"
答案 4 :(得分:0)
使用reduce返回单个键
如果您需要返回单个键,或者在同步之前转换选择,vue-select 提供了一个 reduce 回调,允许您在将所选选项传递给 @input 事件之前转换它。考虑这个数据结构:
let options = [{code: 'CA', country: 'Canada'}];
如果我们想显示国家,但将代码返回给v-model,我们可以使用reduce prop只接收需要的数据。
https://vue-select.org/guide/values.html#transforming-selections