【问题标题】:An array item value taken from input's v-model取自输入的 v-model 的数组项值
【发布时间】:2019-09-30 12:40:15
【问题描述】:

我正在创建一个下拉菜单,用户可以在其中选中多个复选框,并且值将被添加到数组中,然后显示在 DOM 中。

但用户必须能够在输入中编写自己的选项,并且该值也将添加到数组中,然后与其他选项一起显示在 DOM 中。

在选中“其他”复选框之前,应隐藏“其他”输入。

我的想法是添加 : value 属性,该属性将反映输入的 v-model 值,但它不能按我想要的方式工作。

有什么想法吗?感谢您的所有提示。

我做了一个例子 - 在 JSFiddle - https://jsfiddle.net/rxz65s4m/4/

代码:

<script src="https://unpkg.com/vue"></script>
<div id="app">
  <h1>
    What have you eaten today?
  </h1>

  <input type="checkbox" id="first" v-model="selected" value="Fish">
  <label for="first">Fish</label>
  <br />
  <input type="checkbox" id="second" v-model="selected" value="Meat">
  <label for="second">Meat</label>
  <br />
  <input type="checkbox" id="third" v-model="selected" value="Potatoes">
  <label for="third">Potatoes</label>
  <br />

  <!-- Need to take the value from the input -->
  <input type="checkbox" id="fourth" v-model="selected" :value="otherText">
  <label for="fourth">Other</label>
  <!-- this input should be hidden until the checkbox above is checked -->
  <input type="text" v-model="otherText">

  <p>
    {{selected}}
  </p>
</div>

和脚本:

new Vue({
  el: '#app',
  data: {
    selected: [],
    otherText: null
  }
})

编辑: 为了更好地解释:选中“其他”复选框后,用户将能够在位于“其他”复选框旁边的输入中键入内容。在输入中键入的单词应添加到数组中,然后显示在 DOM 中。输入输入应该反应性地改变数组中的值,所以最后应该有例如数组:["Fish", "somethingUserTyped"]

【问题讨论】:

  • otherText 输入按预期工作,您希望的行为是什么?
  • @Slim 谢谢你的评论。我添加了 EDIT 以获得更好的解释。
  • Slim 对不起亲爱的,我指的是@MapeSVK

标签: javascript vue.js vuejs2


【解决方案1】:

您可以使用@change 事件。

比较:https://vuejs.org/v2/guide/forms.html

小提琴:https://jsfiddle.net/mgLrv4kd/1/

new Vue({
  el: '#app',
  data: {
    selected: [],
    otherText: null
  },
  methods: {
    getInput(input) {
      this.selected.push(input);
    }
  }
})
 &lt;input type="text" v-model="otherText" @change="getInput(otherText)"&gt;

【讨论】:

    猜你喜欢
    • 2022-08-13
    • 2016-04-21
    • 2021-03-19
    • 2018-06-13
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2020-04-09
    相关资源
    最近更新 更多