Vue. Js’s instruction

Directives are special Directives with a V-prefix, and the value of Directives is usually a single JavaScript expression (except v-for). The function of an instruction is to react to changes in the value of an expression by affecting the DOM in a cascading manner.

Common Vue directives are:


1. V-text and V-html

V-text displays text data in the label. The data in the data object is output as is, for example:

<span v-text="message"></span>
<! -- Short form -->
<span>{{message}}</span>
Copy the code

Output actual HTML in the template. If you use v-text to output a labeled string, you just want to output the labeled HTML in the page, but you don’t parse the HTML code. If you parse the HTML code, you use v-HTML instructions. Such as:

<p v-text="Message"></p> <! Output text content with HTML tags -->
<p v-html="message"></p> <! -- Output the content of parsed HTML code -->

<script type="text/javascript">
	var app = new Vue({
		el: '#app'.//element
		data: {
			message: 'Hello Vue! ',}})</script>
Copy the code

After executing the above code, the output is as follows:

The output of v-text is: Hello Vue!

The output of v-HTML is: Hello Vue!

Conclusion:

V-text and {{}} expressions render data without parsing labels;

V-html can not only render data, but also parse tags;


2, v – cloak

Function: The V-clock instruction is mainly used to solve the flicker problem of interpolation {{}} before rendering.

In simple terms, when the network is slow and the page is still loading vue.js, this will cause the VUE to render too late, which is the page will display the Vue source code. We can solve this problem with the V-cloak command.

Presentation:

HTML code:

<div id="app">
    {{context}}
</div>
Copy the code

JS code:

<script>
    var app = new Vue({
        el: '#app',
        data: {
            context:'Internet head Gamer's Favorite fitness program'}});</script>
Copy the code

Effect:

In this case, you can use the V-cloak command to solve the flicker problem. The JS code remains the same, just add the V-cloak instruction to the div. Use the V-Cloak directive to set styles that will be removed from the bound HTML element when the Vue instance is compiled.

Code examples:

HTML code:

<div id="app" v-cloak>
    {{context}}
</div>
Copy the code

The CSS code:

[v-cloak]{
    display: none;
}
Copy the code

Cloak the effects of using the V-cloak command:

For simple projects, using the V-Cloak directive is a good way to get around screen flickering. But in large, engineered projects (webpack, Vue-Router) where there is only an empty div element and the contents of the element are routed and mounted, the V-cloak directive is not needed.


3. V-bind

V-bind is used to bind data and element attributes, for example:

<div class="app">
    <a v-bind:href="url">click me</a>
</div>  
Copy the code
var app = new Vue({
    el:'.app'.data: {url:"https://www.baidu.com",}});Copy the code

The value of the attribute is fetched from the Vue instance’s data object. When the corresponding attribute value in the data object changes, the attribute value in the DOM is also updated. You can output the test in the console.

Multiple attributes can be bound to the same DOM element, for example:

<div class="app">
    <a v-bind:href="url" v-bind:class="klass">click me</a>
    <img v-bind:src="imgsrc">
</div>  
Copy the code
var app = new Vue({
    el:'.app'.data: {url:"https://www.baidu.com".imgsrc:"https://cn.vuejs.org/images/logo.png".class:"btn btn-default"}});Copy the code

In addition to a simple type of data, v-bind can also bind an object, for example:

<div class="app">
    <a v-bind:class="{active:isActive}">click me</a>
</div>  
Copy the code

In the above code, the name of the object isActive, indicating the name of the class to be added, isActive is the data in vue, indicating under what circumstances the name of the class to be added, i.e., the corresponding value (isActive value) in the data object of the vue instance is true, To add the active style to the class of the DOM element.

Abbreviations:

The V-bind directive simplifies English colons:, example:

<div class="app">
    <a v-bind:href="url">click me</a>
</div>  
Copy the code

It can be simplified as:

<div class="app">
    <a :href="url">click me</a>
</div>  
Copy the code

4. V-on event binding

4.1. Listening events

You can use the V-ON directive to listen for DOM events and run some JavaScript code when triggered. Sample code:

<div id="app">
  <button v-on:click="counter += 1">Add 1</button>
  <p>{{counter}}</p>
</div>
Copy the code
var vm = new Vue({
  el: '#app'.data: {
    counter: 0}})Copy the code

After the above code runs, each time the button is clicked, the value of the counter property in the data object increases by one.

4.2 Event handling methods

V-on is used to bind events, for example, there is a button that performs some action when clicked:

<div id="app">
	<button v-on:click="myclick">button</button>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {},methods: {
		myclick:function() {
			console.log('hello world')}}Copy the code

The value after V-on :click in

4.3 methods in inline processors

In addition to binding directly to a method, you can also call a method in an inline JavaScript statement:

<div id="app">
  <button v-on:click="say('hi')">Say hi</button>
  <button v-on:click="say('what')">Say what</button>
</div>
Copy the code
new Vue({
  el: '#app'.methods: {
    say: function (message) {
      alert(message)
    }
  }
})
Copy the code

After the above code runs, the say() method is executed whenever both buttons are clicked.

Sometimes you also need to access the raw DOM event in the associative sentence processor. We can pass it to the method with the special variable $event:

<button v-on:click="warn('Form cannot be submitted yet.', $event)">
  Submit
</button>
Copy the code
// ...
methods: {
  warn: function (message, event) {
    // Now we can access the native event object
    if (event) {
      event.preventDefault()
    }
    alert(message)
  }
}
Copy the code

4.4 Multi-event processing method

V-on can bind multiple events, for example:

<div id="app">
	<button v-on="{mouseenter:onenter,mouseleave:leave}">button</button>
</div>
Copy the code

Or it could be written as:

<div id="app">
	<button v-on:mouseenter="onenter" v-on:mouseleave="leave">button</button>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {},methods: {
		onenter:function() {
			console.log('onenter... ')},leave:function() {
			console.log('leave... ')}}})Copy the code

When multiple events are bound, you need to pass in an object whose key name is the name of the event and whose key value is the method to execute the corresponding event.

4.5. Prevent form submission by default

When using a form, when the submit button is clicked, the browser sends a default GET or POST request to the specified page to refresh the entire page. In order to add form validation and prevent the browser from default behavior, you can add the $event parameter to the binding submit method. $event is the event object in the Vue. Vue can recognize it.

<div class="app">
    <form v-on:submit='onSubmit($event)'>
        <input type="text" >
        <button type="submit">submit</button>
    </form>
</div>  
Copy the code
var app = new Vue({
    el:'.app'.data:{
        
    },
    methods: {onSubmit:function(e){
            e.preventDefault(); // Block the browser's default behavior
            console.log("onSubmited"); }}});Copy the code

In Vue, decorators are already wrapped to prevent browser default behavior. You can organize default events by adding the.prevent decorator to the end of the event, for example:

<div id="app">
	<form v-on:submit.prevent="onSubmit($event)">
		<input type="text">
		<button type="submit">submit</button>
	</form>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {},methods: {
		onSubmit: function() {
			console.log('onsubmit.... ')}}})Copy the code

4.6. V-on Event shorthand

V-on can be shortened to the @ symbol, for example:

<div id="app">
	<button v-on:click="myclick">button</button>
</div>
Copy the code

It can be simplified as:

<div id="app">
	<button @click="myclick">button</button>
</div>
Copy the code

4.7. Event modifiers

Calling event.preventDefault() or event.stopPropagation() in the event handler is a very common requirement. While this could easily be done in a method, it’s better if the method has pure data logic instead of dealing with DOM event details.

To solve this problem, vue.js provides event modifiers for V-Ons. As mentioned earlier, modifiers are represented by an instruction suffix beginning with a dot.

  • .stop
  • .prevent
  • .capture
  • .self
  • .once
  • .passive
<! -- Prevent the click event from propagating -->
<a v-on:click.stop="doThis"></a>

<! Submit events no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>

<! -- modifiers can be concatenated -->
<a v-on:click.stop.prevent="doThat"></a>

<! -- only modifiers -->
<form v-on:submit.prevent></form>

<! Add event listener with event capture mode
<! Events triggered by an inner element are processed here before they are processed by the inner element.
<div v-on:click.capture="doThis">.</div>

<! Trigger handler only if event.target is the current element itself -->
<! -- that is, events are not triggered from internal elements -->
<div v-on:click.self="doThat">.</div>

<! Click event will only trigger once -->
<a v-on:click.once="doThis"></a>

<! -- The default behavior of the scroll event (i.e. the scroll behavior) will be triggered immediately -->
<! Instead of waiting for 'onScroll' to finish -->
<! -- This includes' event.preventdefault () '-->
<div v-on:scroll.passive="onScroll">.</div>
Copy the code

4.8. Key modifier

When listening for keyboard events, we often need to check for detailed keystrokes. Vue allows v-ONS to add key modifiers when listening for keyboard events:

<! -- call 'vm.submit()' only if 'key' is' Enter '-->
<input v-on:keyup.enter="submit">
Copy the code

The event use of keyCode has been abolished in Vue, but the keyCode attribute can be used, for example:

<input v-on:keyup.13="submit">
Copy the code

To support older browsers if necessary, Vue provides aliases for most commonly used keycodes:

  • .enter
  • .tab
  • .delete(Capture delete and Backspace keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

Some keys (.esc and all arrow keys) have different keys in IE9, and these built-in aliases should be preferred if you want to support IE9.

You can also customize key modifier aliases using the global config.keyCodes object:

// You can use 'V-on :keyup.f1'
Vue.config.keyCodes.f1 = 112
Copy the code

4.9. System modifiers

You can use the following modifier to implement a listener that fires a mouse or keyboard event only when the corresponding key is pressed.

  • .ctrl
  • .alt
  • .shift
  • .meta

Such as:

<! -- Alt + C -->
<input @keyup.alt.67="clear">

<! -- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
Copy the code

Note that the modifier key differs from the regular key in that, when used with the keyUP event, the modifier key must be in the pressed state when the event is fired. In other words, keyup.ctrl can only be triggered if the other keys are released while CTRL is being held down. Releasing the CTRL alone will not trigger the event. If you want this behavior, use keyCode: keyup.17 for CTRL instead.

.exactThe modifier

The. Exact modifier allows you to control events triggered by the exact combination of system modifiers.

<! -- Trigger even when Alt or Shift is pressed together -->
<button @click.ctrl="onClick">A</button>

<! -- Triggered only when Ctrl is pressed -->
<button @click.ctrl.exact="onCtrlClick">A</button>

<! -- triggered when no system modifier is pressed -->
<button @click.exact="onClick">A</button>
Copy the code

Mouse button modifier

  • .left
  • .right
  • .middle

These modifiers restrict the handler to responding only to a particular mouse button.

4.10. Customize key modifier aliases

You can customize key modifier aliases in Vue via config.keyCodes. For example, because keycode 116 (F5) has a pre-defined alias of F5, pressing F5 in the text input box triggers the prompt method and an alert appears.

<div id="app">
	<input type="text" v-on:keydown.f5="prompt()" />
</div>
Copy the code
Vue.config.keyCodes.f5 = 116;
var vm = new Vue({
	el: '#app'.data: {},methods: {
		prompt: function() {
			alert("Press F5!")}}})Copy the code

5. V-if and V-show conditional rendering

5.1, v – the if

The V-if directive is used to conditionally render a piece of content that will only be rendered if the expression of the directive returns true. Such as:

<div id="app">
	<div v-if="seen">Content that can be controlled</div>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		seen: true}})Copy the code

In the code above, the V-if directive determines whether to insert the div element based on the value (true or false) of the expression seen.

You can use the V-else and V-else directives in conjunction with v-if, for example:

<div id="app">
	<div v-if="score >= 90 && score <= 100">good</div>
	<div v-else-if="score > 60 && score <=90">good</div>
	<div v-else>Don't pass the</div>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		score: 90}})Copy the code

The v-else element must follow the V-if or V-else -if element, and the V-else -if element must follow the V-if element. Neither v-else nor V-else -if can be used alone.

Since v-if is an instruction, it must be added to an element, but if you want to switch between multiple elements, you can use the

<template v-if="ok">
  <h1>Title</h1>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</template>
Copy the code

5.2. Manage reusable elements with keys

Vue renders elements as efficiently as possible, often reusing existing elements rather than rendering them from scratch. This has some other benefits besides making Vue very fast. For example, if a project has two user login methods, you can use V-if to switch between the two login methods.

<div id="app">
	<template v-if="loginType">
		<label>User name:</label>
		<input placeholder="Please enter user name">
	</template>
	<template v-else>
		<label>Email address:</label>
		<input placeholder="Please enter email address">
	</template>
	<button @click="toggleType">Switching the Login Mode</button>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		loginType: true
	},
	methods: {
		toggleType: function() {
			this.loginType = !this.loginType; }}})Copy the code

In the code above, switching loginType will not clear what the user has entered, because both templates use the same element,

So the element is being reused, it’s not being replaced, it’s just replacing the placeholder property in the element. The effect is as follows:

This situation is definitely not practical, so Vue provides a way to solve this problem by adding a key attribute to elements that do not need to be reused, telling Vue that these are two separate elements and not to reuse them. Sample code:

<div id="app">
	<template v-if="loginType">
		<label>User name:</label>
		<input placeholder="Please enter user name" key="username-input">
	</template>
	<template v-else>
		<label>Email address:</label>
		<input placeholder="Please enter email address" key="email-input">
	</template>
	<button @click="toggleType">Switching the Login Mode</button>
</div>
Copy the code

After adding the key attribute to the input, the input field will be re-rendered each time it is toggled, with the following effect:

Because the

5.3, v – show

Vue also provides an option to display elements based on conditions, an example of which is the V-show directive:

<div id="app">Controlled content:<span v-show="ok">Hello</span>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		ok: false}})Copy the code

Unlike v-show, where the element decorated by this directive is always rendered and retained in the DOM regardless of its value, v-show simply toggles the element’s CSS property display: None. The code above looks like this in the browser:

Note here that v-show does not support

5.4. Difference between V-IF and V-show

(1) Explicit implicit process:

Although both directives can display DOM elements dynamically, their execution is quite different:

  • V-if dynamically adds or removes DOM elements to the DOM tree;
  • V-show controls display and hiding by setting the display style attribute of the DOM element.

(2) Compilation process:

  • The V-IF switch has a partial compile/uninstall process in which internal event listeners and subcomponents are destroyed and rebuilt as appropriate;
  • V-show is simply a CSS-BASED switch;

(3) Compilation conditions:

  • V-if is lazy, if the initial condition is false, do nothing; Partial compilation starts only when the condition is true for the first time (partial unmount occurs when the compilation is cached and the next switch occurs);
  • V-show is compiled under any condition (whether the first condition is true or not) and then cached, and DOM elements are preserved;

(4) Performance consumption:

  • V-if has higher switching performance consumption;
  • V-show has a higher initial render performance cost;

(5) Usage Scenarios:

  • V-if is suitable for scenarios where runtime conditions change less;
  • V-show is suitable for frequency switching scenarios.

5.5,

V-if determines whether to load, which can reduce the pressure on the server and load when needed, but will cause higher switching overhead.

V-show adjusts the DISPLAY property of THE CSS of DOM elements, which can make the client operation more smooth, but has higher initial rendering overhead.

V-if Precautions

The official documentation does not recommend that v-if and V-for be used together. When they are used together, v-for has a higher priority than V-if, which means that v-IF will be repeated separately in each V-for loop.


6. V-for list rendering

6.1. Iterate the number group

You can use the V-for directive to render a list based on an array. The V-for instruction requires the special syntax of the “element in array” form, that is, the syntax of item in items, where items are an array of source data and item is the alias of the array element being iterated over. Sample code:

<ul id="app">
	<li v-for="item in list">{{item}}</li>
</ul>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		list: [1.2.3.4.5]}})Copy the code

Running results:

  • 1
  • 2
  • 3
  • 4
  • 5

In the V-for block, we can access all the properties of the parent scope. V-for also supports an optional second parameter, the index of the current item.

<ul id="app">
  <li v-for="(item, index) in items">
    {{ parentMessage }} - {{ index }} - {{ item.message }}
  </li>
</ul>
Copy the code
var vm = new Vue({
  el: '#app'.data: {
    parentMessage: 'Parent'.items: [{message: 'Foo' },
      { message: 'Bar'}]}})Copy the code

Running results:

  • Parent – 0 – Foo
  • Parent – 1 – Bar

It is also possible to use of instead of in as a separator, since it is closer to the syntax of a JavaScript iterator:

<div v-for="item of items"></div>
Copy the code

6.2. Iterate over objects

We can use v-for to iterate over the properties of an object. Example code:

<ul id="app">
  <li v-for="value in object">
    {{ value }}
  </li>
</ul>
Copy the code
new Vue({
  el: '#app'.data: {
    object: {
      name: 'Tom'.age: 20.sex: 'male'}}})Copy the code

Results:

  • Tom
  • 20
  • male

It is also possible to provide a second property name:

<div v-for="(value, name) in object">
  {{ name }}: {{ value }}
</div>
Copy the code

Results:

Name: Tom age: 20 sexCopy the code

You can also use a third parameter as an index:

<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>
Copy the code

Results:

1. What is your name? 2Copy the code

Note: When traversing an Object with v-for, the result of object.keys () is traversed, but its results are not guaranteed to be consistent across the JavaScript engine that passes.

6.3. Iterate over integers

V -for can also accept integers. In this case, it will repeat the template the corresponding number of times.

<div>
  <span v-for="n in 10">{{ n }} </span>
</div>
Copy the code

Results:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10Copy the code

In 6.4,<template>To use the v – for

Similar to v-if, you can use ‘with v-for to loop over a piece of content containing multiple elements. Such as:

<ul>
  <template v-for="item in items">
    <li>{{ item.msg }}</li>
    <li class="divider" role="presentation"></li>
  </template>
</ul>
Copy the code

6.5. Use the Key attribute

When Vue is updating a list of elements rendered using V-for, it defaults to the “update in place” policy. If the order of data items is changed, Vue does not move DOM elements to match the order of data items, but instead updates each element in place and ensures that they are rendered correctly at each index location.

To give Vue a hint that it can keep track of the identity of each node to reuse and reorder existing elements, we need to provide a unique key attribute for each item:

<div v-for="item in items" v-bind:key="item.id">
  <! - content - >
</div>
Copy the code

It is recommended that you provide the key attribute with v-for whenever possible, unless traversing the output DOM content is very simple or you deliberately rely on default behavior for performance gains.

Note for the key attribute:

  • In the V-for loop, the key attribute can only use the number and string types.
  • When using the key, you must use the V-bind attribute to specify the key value.
  • When using a V-for loop in a component, you must specify a unique key attribute value along with the v-for.

6.6. Array update operation

Vue wraps the listening array with mutation methods, which are methods provided by the index group object that change the array’s original data after being called. There are also non-mutation methods, which do not alter the original array but return a new one.

Vue can listen for array mutating methods, so array mutating methods will also trigger view update when called. These methods include:

  • push(): Adds one or more elements to the end of the array and returns the new length;
  • pop(): removes the last element of the array and returns the deleted element;
  • shift(): removes and returns the first element of the array;
  • unshift(): Adds one or more elements to the beginning of the array and returns the new length;
  • splice(): Adds or removes elements from an array;
  • sort(): Sorts the elements of an array;
  • reverse(): reverses the order of the elements in the array;

Non-mutating methods do not change the original array and always return a new array. Non-mutating methods include:

  • filter(): detects numeric elements and returns an array of all elements that match the condition;
  • concat()Concatenate two or more arrays. This method does not change the existing array, but only returns a copy of the concatenated array.
  • slice(): selects part of an array and returns a new array.

So when using the non-mutating method, we can replace the old array with the new one:

vm.lsit = vm.list.filter(function(item){
	return item.msg.match(/Foo/)})Copy the code

In the above code, the new array returned by filter() replaces the array in the Vue instance’s data object. Although the Vue instance’s data object is reassigned, the entire list is not rerendered because Vue implements some clever heuristics to maximize the reuse of DOM elements. So replacing an array with an array of the same elements is very efficient.

However, due to JavaScript limitations, Vue cannot detect changes to the following arrays:

  • When setting an array item directly using an index, for example:vm.items[indexOfItem] = newValue
  • Modify the length of the array directly, for example:vm.items.length = newLength

Here’s an example:

var vm = new Vue({
  data: {
    items: ['a'.'b'.'c']
  }
})
vm.items[1] = 'x' // Not responsive
vm.items.length = 2 // Not responsive
Copy the code

Solve the first type of problem, which sets an array item using an index:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Or use the vm.$set instance method, which is an alias for the global method vue. set
vm.$set(vm.items, indexOfItem, newValue)
Copy the code
// Use the array splice method
vm.items.splice(indexOfItem, 1, newValue)
Copy the code

To solve the second class of problems, which modify the array length property, use the splice method:

vm.items.splice(newLength)
Copy the code

6.7 Update operations on objects

Again, due to JavaScript limitations, Vue cannot detect the addition or deletion of object attributes:

var vm = new Vue({
  data: {
    a: 1}})// 'vm.a' is now responsive

vm.b = 2
// 'vm.b' is not responsive
Copy the code

Vue does not allow dynamic root-level reactive attributes to be added to already created instances. However, you can add reactive properties to nested objects using the vue.set (Object, propertyName, value) method. For example, for:

var vm = new Vue({
  data: {
    user: {
      name: 'Anika'}}})Copy the code

You can add a new age attribute to the nested User object:

Vue.set(vm.user, 'age'.27)
Copy the code

You can also use the vm.$set instance method, which is just an alias for the global vue. set:

vm.$set(vm.user, 'age'.27)
Copy the code

Sometimes you may need to assign more than one new attribute to an existing Object, such as object.assign () or _.extend(). In this case, you should create a new object with the properties of both objects. So, if you want to add new reactive attributes, do this:

vm.user = Object.assign({}, vm.user, {
  age: 27.favoriteColor: 'Vue Green'
})
Copy the code

6.8. Display filtered/sorted results

Sometimes we want to display a filtered or sorted version of an array without actually changing or resetting the original data. In this case, you can create a calculated property to return a filtered or sorted array.

Such as:

<li v-for="n in evenNumbers">{{ n }}</li>
Copy the code
data: {
  numbers: [ 1.2.3.4.5]},computed: {
  evenNumbers: function () {
    return this.numbers.filter(function (number) {
      return number % 2= = =0}}})Copy the code

In cases where computed attributes do not apply (for example, in nested V-for loops) you can use one method:

<li v-for="n in even(numbers)">{{ n }}</li>
Copy the code
data: {
  numbers: [ 1.2.3.4.5]},methods: {
  even: function (numbers) {
    return numbers.filter(function (number) {
      return number % 2= = =0}}})Copy the code

V-model form data binding

7.1. Basic Usage

Two-way data binding is one of the core features of Vue. Vue’s responsive principle is to implement data – > view, while two-way data binding is to do view – > data operations after the previous step. The V-model directive creates two-way data binding on form elements such as ,

V-model ignores the initial values of the value, Checked, and selected attributes of all form elements and uses the Vue instance data as the data source. You can declare the initial values of the form from the data object data in the Vue instance.

The text

<div id="app">
	<input v-model="msg" />
	<p>Results: {{MSG}}</p>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		msg: ' '}})Copy the code

Multiline text

<div id="app">
	<textarea v-model="msg"></textarea>
	<p>Results: {{MSG}}</p>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		msg: ' '}})Copy the code

Interpolation in text areas ({{text}}) does not work, use v-model instead.

Check box

Single check box bound to a Boolean value:

<div id="app">
	<input type="checkbox" v-model="checked" />
	<label>{{ checked }}</label>
</div>
Copy the code
var vm = new Vue({
	el: '#app'.data: {
		checked: false}})Copy the code

Multiple check boxes bound to an array:

<div id='app'>
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>
Copy the code
new Vue({
  el: '#app'.data: {
    checkedNames: []}})Copy the code

The radio button

<div id="app">
  <input type="radio" id="one" value="One" v-model="picked">
  <label for="one">One</label>
  <br>
  <input type="radio" id="two" value="Two" v-model="picked">
  <label for="two">Two</label>
  <br>
  <span>Picked: {{ picked }}</span>
</div>
Copy the code
new Vue({
  el: '#example-4'.data: {
    picked: ' '}})Copy the code

A drop-down box

Radio:

<div id="app">
  <select v-model="selected">
    <option disabled value="">Please select a</option>
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
  <span>Selected: {{ selected }}</span>
</div>
Copy the code
new Vue({
  el: '#app'
  data: {
    selected: ' '}})Copy the code

When multiple:

<div id="app">
  <select v-model="selected" multiple style="width: 50px;">
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
  <br>
  <span>Selected: {{ selected }}</span>
</div>
Copy the code
new Vue({
  el: '#app'.data: {
    selected: []}})Copy the code

Dynamic options for rendering with V-for:

<select v-model="selected">
  <option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
  </option>
</select>
<span>Selected: {{ selected }}</span>
Copy the code
new Vue({
  el: '#app'.data: {
    selected: 'A'.options: [{text: 'One'.value: 'A' },
      { text: 'Two'.value: 'B' },
      { text: 'Three'.value: 'C'}]}})Copy the code

7.2. Value Binding

For radio buttons, check boxes, and select box options, the value of the V-model binding is usually a static string (it can also be a Boolean value for check boxes) :

<! -- "picked" is the string "A" -->
<input type="radio" v-model="picked" value="a">

<! -- 'toggle' is true or false -->
<input type="checkbox" v-model="toggle">

<! When the first option is selected, 'selected' is the string "ABC" -->
<select v-model="selected">
  <option value="abc">ABC</option>
</select>
Copy the code

But sometimes we might want to bind a value to a dynamic property of a Vue instance, using V-bind, and the value of the property may not be a string.

Check box

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>
Copy the code
// when selected
vm.toggle === 'yes'
// When not selected
vm.toggle === 'no'
Copy the code

The true-value and false-value attributes here do not affect the value attribute of the input control because the browser does not include unchecked checkboxes when submitting the form. If you want to ensure that one of these two values on the form can be submitted (such as “yes” or “no”), use the radio button instead.

The radio button

<input type="radio" v-model="pick" v-bind:value="a">
Copy the code
// when selected
vm.pick === vm.a
Copy the code

Drop – down box options

<select v-model="selected">
    <! Inline object literals -->
  <option v-bind:value="{ number: 123 }">123</option>
</select>
Copy the code
// when selected
typeof vm.selected // => 'object'
vm.selected.number / / = > 123
Copy the code

7.3. Modifiers

.lazy

By default, v-Model synchronizes the value of the input field with the data each time the input event is triggered (except when the input method combines text as described above). You can change to synchronization using the change event by adding the lazy modifier:

<! Update "change" instead of "input" -->
<input v-model.lazy="msg" >
Copy the code

.number

If you want to automatically convert user input values to numeric types, you can add the number modifier to the V-Model:

<input v-model.number="age" type="number">
Copy the code

This is often useful because even when type=”number”, the value of the HTML input element always returns a string. If the value cannot be resolved by parseFloat(), the original value is returned.

.trim

If you want to automatically filter whitespace entered by the user, you can add the trim modifier to the V-model:

<input v-model.trim="msg">
Copy the code