具有选择输入的Vue v模型

时间:2020-08-14 00:39:34

标签: javascript html vue.js drop-down-menu v-model

我试图在我的选择输入中包含任何选项以设置为对象中的值。我试图为此目的使用v模型,但我不确定如何。到目前为止,我已经尝试过这样做。

<div class="select-wrapper">
  <select required name="category" id="category" @change="(e) => $emit('input', e.target.value)">
      <option value="" selected="selected">Category*</option>
      <option value="attendee">Attendee</option>
      <option value="distributor">Distributor</option>
      <option value="sponsor">Sponsor</option>
      <option value="media/analyst">Media/Analyst</option>
      <option value="university">University</option>
      <option value="other">Other</option>
  </select>
 </div>

2 个答案:

答案 0 :(得分:1)

需要一个道具来绑定选定的值,并将该道具传递给v-model。例如

<template>
  <div>
    <pre>category = {{ category }}</pre>
    <select required name="category" id="category" v-model="category">
      <option value="">Category*</option>
      <option value="attendee">Attendee</option>
      <option value="distributor">Distributor</option>
      <option value="sponsor">Sponsor</option>
      <option value="media/analyst">Media/Analyst</option>
      <option value="university">University</option>
      <option value="nxp">NXP</option>
    </select>
  </div>
</template>

<script>

export default {
  data() {
    return {
      category: null
    };
  }
};
</script>

编辑:plunker

答案 1 :(得分:1)

您应该在组件中添加value属性:

<div class="select-wrapper">
  <select required name="category" id="category" @change="(e) => $emit('input', e.target.value)">
      <option value="" selected="selected">Category*</option>
      <option value="attendee">Attendee</option>
      <option value="distributor">Distributor</option>
      <option value="sponsor">Sponsor</option>
      <option value="media/analyst">Media/Analyst</option>
      <option value="university">University</option>
      <option value="other">Other</option>
  </select>
 </div>
<script>

export default {
 props:value
};
</script>

并将其用于父组件,如:

<my-select v-model="category"/>
...
<script>

export default {
  data() {
    return {
      category: ''
    };
  }
};
</script>