【问题标题】:Vue store multiple values as an arrayVue 将多个值存储为数组
【发布时间】:2020-09-05 19:07:25
【问题描述】:

有没有办法在提交时在数据返回中存储多个值。

查看

<div id="app">
  <input type="text" v-model="inserted" placeholder="Insert Name">
  <button type="submit" v-on:click='submit();'>SUBMIT</button>
</div>

脚本

new Vue({
  el: "#app",
  data: {
   inserted:[], /** each name submitted should be stored over here **/
   /** if the first name was submitted as DAVID and second name was submitted as JOHN **/
   /** inserted[] should consists of both values as ["DAVID", "JOHN"] **/
  },
  methods: {
    submit(){
    console.log('value submitted');
    }
  }
})

下面是我在JSFIDDLE上的代码

https://jsfiddle.net/ujjumaki/ypbc2vf6/12/

【问题讨论】:

    标签: arrays vue.js


    【解决方案1】:

    我花了比Nino 更长的时间,但这是一个完整的工作示例,并添加了一些验证,因此您不要添加空名称:


    您可以为其他类型的 vue 变量创建输入,例如 f.e. name。在submit() 中,如果它不为空,则将其添加到您的数组中:

    new Vue({
      el: "#app",
      data: {
       inserted:[], /* each name submitted should be stored over here */
       /* if the first name was submitted as DAVID and second name was submitted as JOHN*/
       /* inserted[] should consists of both values as ["DAVID", "JOHN"] */
       name: "",
      },
      methods: {
      	submit() {
          if (this.name.length > 0) { 
            this.inserted.push(this.name);
        }
        }
      }
    })
    body {
      background: #20262E;
      padding: 20px;
      font-family: Helvetica;
    }
    
    #app {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      transition: all 0.2s;
    }
    
    li {
      margin: 8px 0;
    }
    
    h2 {
      font-weight: bold;
      margin-bottom: 15px;
    }
    
    del {
      color: rgba(0, 0, 0, 0.3);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <input type="array" v-model="name" placeholder="Insert Name">
      <button type="submit" @click='submit();'>SUBMIT</button>
      
      <p>Message is: {{ inserted }}</p>
    </div>

    【讨论】:

      【解决方案2】:

      当然,只需将您的输入绑定到 toInsert 数据属性,然后在提交时将其推送到 inserted

      <input v-model="inserted">
      <button @click="submit">submit</button>
      
      new Vue({
        data: {
          inserted: [],
          toInsert: '',
        },
        methods: {
          submit() {
      
            // save the value
            this.inserted.push(this.toInsert);
      
            // clean the input
            this.toInsert = '';
      
          }
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2019-07-25
        • 2016-05-01
        • 1970-01-01
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        相关资源
        最近更新 更多