【问题标题】:How to assign a v-model on v-for (from bootstrap vue example)如何在 v-for 上分配 v-model(来自 bootstrap vue 示例)
【发布时间】:2020-02-25 04:57:00
【问题描述】:

我正在使用 vue-bootstrap 使用 v-for 指令创建一些输入字段。我正在尝试做的基本上与this link 中提供的示例相同,但我不知道如何将我收集的数据获取到 v-model 指令中(我的意思是,从输入中获取数据)。

我可以手动完成并分配每个字段并将其映射到我的对象的 v-model 中,但如果有更好的方法来解决这个问题,那将非常有帮助。

这是几乎完全从示例页面复制的代码 (vue-js),但我的修改失败(使用 cmets)

<template>
  <b-container fluid>
    <code>{{result}}</code>
    <b-row class="my-1" v-for="type in types" :key="type">
      <b-col sm="3">
        <label :for="`type-${type}`">Type {{ type }}:</label>
      </b-col>
      <b-col sm="9">
        <!-- here I modified the v-model part -->
        <b-form-input :id="`type-${type}`" :type="type" :v-model="`result.${type}`"></b-form-input>
      </b-col>
      <!-- here I added the same "v-model" that I placed into the previous line -->
      <p>{{`result.${type}`}}</p>
    </b-row>
  </b-container>
</template>

<script>
  export default {
    data() {
      return {
        // here I placed the result object and I expected to obtain something like this:
        /*
result: {
text: "the text",
password: "the password" 
...
...
}
        */
        result: {},
        types: [
          'text',
          'password',
          'email',
          'number',
          'url',
          'tel',
          'date',
          `time`,
          'range',
          'color'
        ]
      }
    }
  }
</script>

谁能解释我做错了什么?我试图在 v-for 语句中找到 "`type-${type}`" 的文档,但我找不到。

【问题讨论】:

    标签: javascript vue.js vuejs2 bootstrap-vue


    【解决方案1】:

    result初始化为:

    result: {
      text: '',
      password:, '',
      email: '',
      number: '',
      url: '',
      tel: '',
      date: '',
      time: '',
      range: '',
      color: ''
    }
    

    在您的模板和v-model 中,使用[] 而不是. 进行密钥访问,即result.${type} => result[type]

    还要注意v-model 本身就是一个指令,所以你不需要在这里使用v-bind(:):

    <b-form-input :id="`type-${type}`" :type="type" v-model="result[type]">
    </b-form-input>
    

    【讨论】:

    • 它不起作用。我所做的是按照建议初始化结果,然后将原始行更改为:&lt;b-form-input :id="type-${type}" :type="type" :v-model="result[type]"&gt;&lt;/b-form-input&gt; 但结果对象未在任何输入上更新
    • 这行&lt;p&gt;{{ result.${type} }}&lt;/p&gt;改了吗?
    • 这是我放置的,而不是那行 &lt;p&gt;{{result[type]}}&lt;/p&gt;,但它现在没有显示任何内容
    • 对于v-model,前面不需要冒号。它本身就是一个指令。就做v-model="result[type]"
    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 2018-06-13
    • 2020-07-01
    • 2019-04-30
    • 2018-11-08
    • 2020-07-18
    • 2019-12-16
    • 2016-11-12
    相关资源
    最近更新 更多