【问题标题】:How to record multidimensional arrays from forms with Vue?如何使用 Vue 从表单中记录多维数组?
【发布时间】:2018-12-14 19:30:39
【问题描述】:

所以我有这个样本:

<div class="form-item">
  <label for="list-0"><?php _e('List 0', 'test'); ?></label>
  <input name="list[0]" type="text" id="list-0" value="">
</div>
<div class="form-item">
  <input type="checkbox" name="list[0][is-current]" id="list-0-current" value="yes">
  <label for="list-0-current"></label>
</div>

我想要的是这样的:

list:[
    [value, is_current] // say 'John', yes
    ,[value, is_current] // say 'Francis', false
    ,[value, is_current] // say 'Bob', yes
]

在 Vue 中,您可以在数据中使用数组:

var vueapp = new Vue({
  el: '#form'
  ,data:{
    form:{
      list:[]
      //[...] etc..

然后在您的字段中,您只需在列表的每个字段中使用v-model="form.list"。但这只会记录一个平面数组,而我需要一种方法来拥有一个多重数组。可能吗?怎么样?

【问题讨论】:

    标签: javascript html forms vue.js


    【解决方案1】:

    制作一个对象:

     data: {
          form: [{}]
     },
    

    如果这是你的数组:

    list = [
        [value, is_current],
        [value, is_current],
        [value, is_current],
    ];
    

    然后遍历这个数组并将每个内部数组添加到对象中:

      list.forEach(function(element) {
            that.form.push({value: element[0], key: element[1]});
      });
    

    请参阅此小提琴以供参考:

    https://jsfiddle.net/mnd8ojLh/1/

    【讨论】:

    • 值在我的例子中不是预定义的:如你所见,它们也来自用户输入
    • 是吗?这是一样的,填充的只是为了形象化小提琴。何时何地填充完全取决于您。如果对您有帮助,我已从答案中删除了示例输入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2020-09-29
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多