【问题标题】:How to get the value of one input field in a "v-for" of multiple inputs如何在多个输入的“v-for”中获取一个输入字段的值
【发布时间】:2021-08-21 14:39:36
【问题描述】:

我在 v-for 指令中生成了多个文本输入,我已将其附加到一个 v-model 变量,如下所示。我在各个输入上有一个按钮,可以打印当前工作输入的值。最终我想在不影响其他输入的情况下提取所选输入的值。

但显然对一个输入所做的任何更改都会影响所有输入。我对如何实现这一目标感到非常困惑。任何帮助将不胜感激。

我尝试的代码如下所示。

<template>
  <div id="app">
    <div v-for="i in 5" :key="i">
      <input v-model="text" type="text" :key="i" />
      <button @click="printText">print</button> <span>{{ text }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: "",
    };
  },
  methods: {
    printText() {
      console.log(this.text);
    },
  },
};
</script>

【问题讨论】:

  • 制作text 一个数组,然后执行v-model="text[i]"

标签: vue.js vuejs2


【解决方案1】:

在 v-for 中使用 v-model 时,取一个数组而不是简单变量

点击通过函数调用传递索引

尝试使用

<template>
  <div id="app">
    <div v-for="i in 5" :key="i">
      <input v-model="text[i]" type="text"/>
      <button @click="printText(i)">print</button> <span>{{ text[i] }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: [],
    };
  },
  methods: {
    printText(index) {
      console.log(this.text[index]);
    },
  },
};
</script>

【讨论】:

    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多