我如何使选择下拉显示当前选择的值在Vue?



类似于Select always first value Select vue.js,但我正在制作一个自定义组件。

我有一个SFC与一些额外的调试输出

<script>
export default {
props: ['modelValue', 'options'],
emits: ['update:modelValue']
}
</script>
<template>
<div>

<select
:value="modelValue"
@change="$emit('update:modelValue', JSON.parse($event.target.value))"
>
<option value="" disabled>no selection</option>
<option v-for="option in options" :value="JSON.stringify(option)" :selected="JSON.stringify(modelValue) === JSON.stringify(option)">X{{JSON.stringify(option)}}X{{JSON.stringify(modelValue) === JSON.stringify(option)}}</option>
</select>
{{modelValue}}
</div>
</template>

和调用组件

<script>
import CustomInput from './CustomInput.vue'
export default {
components: { CustomInput },
data() {
return {
message: '',
blah: [
{a:"a"},
{b:2},
{c:{d:1}},
]
}
},
computed: {
theMessage() {
return JSON.stringify(this.message);
}
}
}
</script>
<template>
<CustomInput v-model="message" :options="blah"/> {{ theMessage }}
</template>

但是我不能让选中的项目出现在下拉菜单中,即使"标签"显示它应该被选中。

游乐场

你可以在子组件中使用v-model,并使用computed setter/getter将事件冒出给父组件

App.vue

<script>
import CustomInput from './CustomInput.vue'
export default {
components: { CustomInput },
data() {
return {
message: '',
blah: [
{a:"a"},
{b:2},
{c:{d:1}},
]
}
},
}
</script>
<template>
<CustomInput v-model="message" :options="blah" /> {{ message }}
</template>

CustomInput.vue

<script>
export default {
props: ['modelValue', 'options'],
emits: ['update:modelValue'],
computed: {
internalValue: {
get() {
return this.modelValue;
},
set(newVal) {
this.$emit('update:modelValue', newVal)
}
}
}
}
</script>
<template>
<div>
<select
v-model="internalValue"
>
<option value="" disabled>no selection</option>
<option v-for="option in options" :value="JSON.stringify(option)" :selected="JSON.stringify(modelValue) === JSON.stringify(option)">{{
option}}</option>
</select>
</div>
</template>

(我不确定你的JSON。字符串很有用)

最新更新