vue.js - 向父级发送下拉值
问题描述
我的父母有这个表格:
<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
机制将 to 的输出绑定vue-select
到form.country
容器中。
在CountryDropdown
,实施v-model
:
- 添加一个
prop
命名的value
1️⃣,并将其绑定到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
到它,在选择时更新form.country
为所选国家countryCode
:
<CountryDropdown v-model="form.country" />
推荐阅读
- ios - 如何从 SafeViewArea 中删除上边距 | 反应原生 | iPhoneX
- c# - 如何解决hangfire中只能在后台调用公共方法?
- python - 使用 python 的 psycopg2 将数组写入 Postgres
- sql - SQL 服务器更新表
- apache-spark - 在 pySpark 我得到 py4j.protocol.Py4JError: py4j.Py4JException: Method isBarrier([]) 不存在
- model-view-controller - 在 MVC 应用程序登录页面中加载部分视图
- python - 如何在 Python 中计算机器学习回归任务的预测区间
- gcc - 在链接器脚本中定义了内存来源和长度
- javascript - 如何将我的 ajax 响应值插入到特定的 div 元素?
- apache - REQUEST_URI 填充有默认文件 (DirectoryIndex) /index.html