Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create input name field with string-variable schema in Vue Js?

I use VueJs, i need to extract javascript variable to generate hidden fields.

But i need to set the name by the index of the variable.

I want to use zig-zag naming schema.

like,

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

Javascript Variable:

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

Foreach with Variable to Generate Hidden Fields :

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

Here, :name is a dynamic instance for access vuejs values. index is vuejs variable but "segment" is not a vuejs variable, its actually a string.

But i need this schema to generate array of inputs.

Is this possible ?

Or Any other solutions are there ?

Thanks in Advance !

like image 299
Shankar Thiyagaraajan Avatar asked Dec 09 '16 05:12

Shankar Thiyagaraajan


People also ask

How do I get input value from Vue?

To get an input value in Vue, we can use the v-model directive to set up a two-way binding between the value and a variable. Every time the user changes the text in the input field, the text variable will be updated automatically. We can then use this variable to perform an action or display information.

How do I declare a variable in the method Vuejs?

if you define global variable then you can easily access global variable in vuejs app. We will define global variables using vue js mixin. using mixin we will declare all variables in data method. then we will use in our app vue object.

What is @input in VUE JS?

It provides two-way data binding by binding the input text element and the value binded to a variable assigned.


1 Answers

To create input elements with dynamic names by index, you can use the + in a JS expression to concatenate:

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

Generates:

<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">

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

like image 180
Jenna Pederson Avatar answered Oct 02 '22 17:10

Jenna Pederson