【问题标题】:How to create input name field with string-variable schema in Vue Js?如何在 Vue Js 中使用字符串变量模式创建输入名称字段?
【发布时间】:2016-12-09 05:59:55
【问题描述】:

我使用 VueJs,我需要提取 javascript 变量来生成隐藏字段。

但我需要通过变量的索引来设置名称。

我想使用 zig-zag 命名模式。

喜欢,

 <input type="text" name="segment[{index}][field_name]" :value="{value}">

Javascript 变量:

    var test_template = {
                        0: {
                            nb: 2
                        },
                        1: {
                            nb: 1
                        },
                        2: {
                            nb: 4
                        }
                    };

使用变量生成隐藏字段的 Foreach :

    <div v-for="(a,index) in test_template" class="row">            
      <input type="hidden" :name="segment[index][nb]" :value="a.nb">
   </div>

这里,:name 是访问 vuejs 值的动态实例。 index 是 vuejs 变量,但 "segment" 不是 vuejs 变量,它实际上是一个字符串。

但我需要这个模式来生成输入数组。

这可能吗?

或者还有其他解决方案吗?

提前致谢!

【问题讨论】:

  • 你试过segment + a.nb 吗?

标签: javascript vue.js vuejs2


【解决方案1】:

我遇到了和你一样的问题,我就是这样解决的!

在你的 vue 实例中创建一个这样的方法

getInputName(index, dataName){
      return "items["+index+"]["+dataName+"]";
    }    

那么你可以这样使用它:

<input v-bind:name="getInputName(index, 'name')" type="text" v-model="item.name">
<input v-bind:name="getInputName(index, 'price')" type="text" v-model="item.price">

这会给你这个帖子结果:

"items" =>[
    0 =>[
      "name" => "test"
      "price" => "23"
    ],
    1 =>[
      "name" => "jakke"
      "price" => "99,2312"
    ]
]

就是这样……

干杯, 西普曼

【讨论】:

    【解决方案2】:

    要通过索引创建具有动态名称的输入元素,您可以在 JS 表达式中使用 + 进行连接:

    <div v-for="(a,index) in test_template" class="row">            
      <input type="hidden" :name="'segment[' + index + '][nb]'" :value="a.nb">
    </div>
    

    生成:

    <input type="hidden" name="section[0][nb]" value="2">
    <input type="hidden" name="section[1][nb]" value="1">
    <input type="hidden" name="section[2][nb]" value="4">
    

    见:https://vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions

    【讨论】:

    • 也可以使用JS6插值。 :name="`segment[${index}][nb]`"
    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 2014-12-13
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多