Vue.js:多个输入中的v-model数组 [英] Vuejs: v-model array in multiple input

查看:770
本文介绍了Vue.js:多个输入中的v-model数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个附加了v模型的输入文本字段,每当有人单击添加"按钮时,就会将另一个输入文本添加到附加了相同v模型的DOM上.我以为可以得到v模型值的数组,但是它只能得到第一个v模型输入的值:

I have an input text field with a v-model attached, and every time someone hits the "Add" button, another input text get added to the DOM with the same v-model attached. I thought I'd then get an array of the v-model values, but it only gets the value of the first v-model input:

<div id="app">
  <div id="references">
    <input v-model="references" type="text">
  </div>
  <button @click="addReference">Add</button>
</div>

我添加到dom的html由addReference方法触发:

The html I append to the dom is triggered by the addReference method:

addReference: function(e) {
  e.preventDefault();
  console.log(this.references);
  var inputEl = '<input v-model="references" type="text">';
  $('#references').append(inputEl);
}

这是Vuejs无法做的事情吗?使用Vuejs从动态dom元素中收集值是否有其他方法?

Is this something Vuejs can't do? Is there a different approach of gathering values from dynamic dom elements with Vuejs?

new Vue({
  el: "#app",
  data: {
    references: "text"
  },
  methods: {
    addReference: function(e) {
      e.preventDefault();
      console.log(this.references);
      var inputEl = '<input v-model="references" type="text">';
      $('#references').append(inputEl);
    }
  }
})

input {
  display: block;
  margin: 1px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
  <div id="references">
    <input v-model="references" type="text">
  </div>
  <button @click="addReference">Add</button>
</div>

推荐答案

您也考虑使用DOM,这很难打破地狱的习惯. Vue建议您首先处理它的数据.

You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.

很难说出您的具体情况,但是我可能会使用v-for并制作一个finds数组来推送到我需要的更多内容.

It's kind of hard to tell in your exact situation but I'd probably use a v-for and make an array of finds to push to as I need more.

这是我设置实例的方式:

Here's how I'd set up my instance:

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: '' });
    }
  }
});

这是我设置模板的方式:

And here's how I'd set up my template:

<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value" :key="index">
  </div>
  <button @click="addFind">
    New Find
  </button>
</div>

尽管,我会尝试在key上使用除index之外的其他内容.

Although, I'd try to use something besides an index for the key.

以下是上述示例: https://jsfiddle.net/crswll/24txy506/9/

这篇关于Vue.js:多个输入中的v-model数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆