首页 > 解决方案 > 向父级发送下拉值

问题描述

我的父母有这个表格:

<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.jsvuejs2nuxt.jsvue-select

解决方案


您可以使用 Vue 的v-model机制将 to 的输出绑定vue-selectform.country容器中。

CountryDropdown,实施v-model

  1. 添加一个prop命名的value1️⃣,并将其绑定到vue-select.value2️⃣
  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" />

演示


推荐阅读