我的 parent 身上有这张表格:
<template>
<b-form @submit="onSubmit">
<CountryDropdown/>
</b-form>
</template>
<script>
import ...
export default {
form: {
country: ''
}
}
</script>
这是我使用 vue-select
的下拉组件:
<template>
<v-select label="countryName" :options="countries" />
</template>
<script>
export default {
data() {
return {
countries: [
{ countryCode: 'EE', countryName: 'Estonia' },
{ countryCode: 'RU', countryName: 'Russia' }
]
}
}
}
</script>
我需要将 countryCode
值传递给其父级的 form.country
。我尝试使用 $emit
,但我似乎无法弄清楚如何选择
它将设置父值,而不是在提交时设置。
编辑:
提交的解决方案效果很好,我将在此处添加我的解决方案:
我向我的 v-select 添加了一个输入事件:
<v-select @input="setSelected" ... />
在我的脚本中,我定义了 selected 和 setSelected 方法:
data()
return
selected: ''
setSelected(value) {
this.selected = value.countryCode
this.$emit("selected", value.countryCode)
}
在父级中:
<CountryDropdown v-on:selected="getCountry />
和父脚本:
getCountry(country) {
this.form.country = country
}
最佳答案
你可以使用Vue的v-model
将 vue-select
的输出绑定(bind)到容器中的 form.country
的机制。
在CountryDropdown
中,实现v-model
:
- 添加一个名为
value
1️⃣ 的prop
,并将其绑定(bind)到vue-select.value
2️⃣ - 发出具有所需值的
input
事件。在本例中,我们希望发出countryCode
作为值。 3️⃣
<template>
<v-select
:value="value" 2️⃣
@input="$emit('input', $event ? $event.countryCode : '')" 3️⃣
/>
</template>
<script>
export default {
props: ['value'], // 1️⃣
}
</script>
现在,CountryDropdown
的容器可以将 form.country
绑定(bind)到它,将 form.country
更新为所选国家/地区的 countryCode
选择后:
<CountryDropdown v-model="form.country" />
关于vue.js - 向父级发送下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62277847/