Vue : v-model directive

Introduction

We forward the user action to the view application with the directive “v-on:”, after processing the data to update the user interface, we pass the data from the application by interpolation or directive v-bind. Each of these individual procedures represents one-way data forwarding. However, data entry fields are specific, as they need to pass data in both directions, so both directives are required on the same element.
In the following example, the form data is passed to the data object with the “v-on: input” directive, while the data modified from the application itself updates the value in the HTML input with the “v-bind: value” directive.

<div id = "app"
     <input v-on:input = "valuekeeper = $ event.target.value" v-bind:value = "valuekeeper">
</ Div>
<Script>
     new Vue ({
       el: '#app',
       data: {
         valuekeeper: 'some text'
       }
       methods: {
         reset () {
           valuekeeper= '';
         }
       }
     })
</script>

Within Vue.js there is a directive that covers this procedure called “v-model”, with which the code seems much simpler to use, instead of:

<input v-on:input="valuekeeper= $event.target.value"   v-bind:value="valuekeeper">

we use a simpler and simpler syntax:

<input v-model="valuekeeper">

REMARK:
The “v-model” directive will ignore the initial value defined on some element of the form (selected and checked) because it considers the “given” property as the main source. Therefore, if we want to declare an initial value on an element of a form, we need to do it, within the “data” property, or to associate the value with the “v-bind” directive.

Example

HTML

<div id="app3">
  <h4>Initial setting of radio input values</h4>
  <div class="form-check">
    <label class="form-check-label">
      <input class="form-check-input" type="radio"  v-model="show" v-bind:value="true">
      Show item
    </label>
  </div>
  <div class="form-check">
    <label class="form-check-label">
      <input class="form-check-input" type="radio" v-model="show" v-bind:value="false">
      Hide item
    </label>
  </div>
  <div class="kvadrat" v-if="show"></div>
</div>

SCSS

.kvadrat{
  width: 100px;
  height: 100px;
  background-color: red;
}
#app3{
	padding: 2rem;
}

Babel

var app3 = new Vue({
          el: "#app3",
          data: {
            show: true
          }
      });

Syntax

The v-model directive can only be used with the following HTML elements of input, select, and text area.

a) Textbox

<input v-model="message" placeholder="edit me">

b) Textarea

<textarea v-model="message" placeholder="add multiple lines"></textarea>

REMARK:
Interpolation is not possible with the textarea element of {{text}}
<textarea>{{text}}</textarea>

c) Checkbox

Single checkbox

If there is only one chekcbox field, the “v-model” directive will treat it as a boolean value, and will ignore the value entered (for example: value = “foo”), so the choice can be either “true” or “false” .

Example

HTML

<div id="example">
	<input id="proba" type="checkbox" value="foo" v-model="isChecked">
	<label for="proba">Click Me</label>
	<p>{{ isChecked }}</p>
</div>

SCSS

#example {
	padding: 2rem;
}

Babel

new Vue({
  el: '#example',
  data: {
    isChecked: false
	}
})

Multiple checkbox

If you have multiple checkboxes that share the same model, then those fields will populate a string with the values of all the checkboxes, so make sure that the “given” property is defined as a string.

Example

HTML

<div id='example'>
            <input type="checkbox" id="alen" value="alen" v-model="selectworker">
            <label for="alen">Alen</label>
            <input type="checkbox" id="joe" value="joe" v-model="selectworker">
            <label for="joe">Joe</label>
            <input type="checkbox" id="mike" value="mike" v-model="selectworker">
            <label for="mike">Mike</label>
            <br>
            <span>The workers selected are: {{ selectworker }}</span>
        </div>

SCSS

#example {
	padding:2rem;
	
}

Babel

new Vue({
  el: '#example',
  data: {
    selectworker: []
  }
})

d) Radio input

<input type="radio" id="alen" value="Alen" v-model="selectWorker">

Example

HTML

<div id="app">
	<input type="radio" id="alen" value="Alen" v-model="selectWorker">
	<label for="alen">Alen</label>
	<br>

	<input type="radio" id="mike" value="Mike" v-model="selectWorker">
	<label for="mike">Mike</label>
	<br>

	<span>Selected worker: {{ selectWorker }}</span>
</div>

SCSS

#app {
	padding:2rem;
}

Babel

new Vue({
  el: '#app',
  data: {
    selectWorker: ""
  }
})

e) Select

<select v-model = "choice">
   <option disabled value = ""> Select one option </option>
   <option> A </option>
   <option> B </option>
   <option> C </option>
</select>
<span> You have selected: {{choice}} </span>
 
<script>
new Vue ({
   el: '...',
   data: {
     Choice: ''
   }
})
</script>

Example

If multiple is defined, then the required “data” property is defined as a string:

<select v-model = "selection" multiple>
   <option> A </option>
   <option> B </option>
   <option> C </option>
</select>
<span> {{choice}} </span>
 
<span> Selected: {{choice}} </span>
<script>
new Vue ({
     el: '#app',
     data: {
         Choice: []
     }
})
</script>

Example

HTML

<div id="app">
<select v-model="choise">
	<option v-for="option in options" v-bind:value="option.value">
		{{ option.naziv }}
	</option>
</select>
<span>It's the workers' daily wage: {{ choise }}</span>
</div>

SCSS

#app {
	padding: 2rem;
}

Babel

new Vue({
  el: '#app',
  data: {
    choise: '100',
    options: [
      { naziv: 'Mike', value: '100' },
      { naziv: 'Joe', value: '200' },
      { naziv: 'Alen', value: '300' }
    ]
  }
})

v-model modifiers

Modifiers are special keywords that affect listing in some way. There are three modifiers that can be used with this directive:

.trim

When using this modifier, any start, end, or multiple empty spaces will be removed in the input field before the value is synchronized with the “data” property.

<input type="text" v-model.trim="name">

Example

HTML

<div id="app">
	<input type="text" v-model.trim=unos>	
	<p>The value of the listing has been trimmed and now the listing is like this: <br> <span id="izlaz">{{entry}}</span></p>
</div>

SCSS

#app {
	padding:2rem;
	input {
		width:20rem;
	}
	#izlaz{
		background-color: #b3db3b;
		padding: 0.4rem 0;
		display: inline-block;
	}
}

Babel

new Vue({
      el: '#app',
      data: {
        entry: "     Alen is  Cool     "
      }
    })

.lazy

By default, the v-model is processed every time a keypress input event is triggered. If we do not want input through the input element to be automatically synchronized with the “data” property for each character entered, but to be synchronized only after the input is completed (press Enter or otherwise out of focus), then we need to use a modifier. lazy

<input type="text" v-model.lazy="message">

.number

JavaScript treats the input value through an “input” element of type “text” as “string”, so if we are working with numbers, it is necessary to cast each entry in “number”. It is this modifier that ensures that the entry is always automatically switched to a number, which would be equivalent to invoking the javascript function “parseInt ()”.

<div id = "app">
    <input v-model.number = "a">
    <p> The variable "b" is always greater than 10 and is {{b}} </p>
</div>
 
<script type = "text / javascript">
new Vue ({
     el: '#app',
     data: {
        a: 1,
     },
     computed: {
        b: function () {
              return this.a + 10
        }
     }
}
</script>

Failure to use this modifier would result in an illogical result. So, for example, if you entered a value of 5 to change “a”, the value of “b” would be 510, because javascript would perform string concatenation instead of adding operations.

REMARK:
If an input element with a defined number type is used, this modifier need not be used, as Vue.js automatically casts to number.

Dynamic value binding

Radio buttons, checkboxes and select generally use predefined values (string or boolean); however, there may be a need to bind some dynamic value. In this case, we also use the “v-bind” directive, which allows us to bind the input to non-string values as well.

a) radio buttons

<input type="radio" v-model="pick" v-bind:value="a">
// when checked:
vm.pick === vm.a

Example

HTML

<div id="app">
	<template v-for="worker in workers">
		<label>	<input type="radio"  v-bind:value="worker" v-model="selectworker">  {{worker}}</label>
		<br>
	</template>
	<span>Selected Worker: {{ selectworker }}</span>
</div>

SCSS

#app {
	padding:2rem;
}

Babel

new Vue({
  el: '#app',
  data: {
		workers: ["Alen", "Joe"],
    selectworker: ""
  }
})

b) select

<select v-model="selected">
  <!-- inline object literal -->
  <option v-bind:value="{ number: 123 }">123</option>
</select>
 
// when selected:
typeof vm.selected // => 'object'
vm.selected.number // => 123
Likes:
15 0
Views:
1815
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

Your email address will not be published. Required fields are marked *