Vue note 2: basic grammar

Vue note 2: basic grammar

1. Interpolation (dynamic content)

Mustache syntax (double braces)

Insert the text data in data into HTML. At this time, the data is responsive.

<span>Message: {{ msg }}</span>
<span>{{firstName}}{{lastName}}</span>
<span>{{firstName+lastName}}</span>
<span>{{firstName+""+lastName}}</span>
//Using JavaScript expressions
<h2> {{counter*2}}</h2>
<h2>{{ number + 1 }}</h2>
<h2>{{ ok ? 'YES' : 'NO' }}</h2>
<h2>{{ message.split('').reverse().join('') }}</h2>

instructions

  • v-once: perform one-time interpolation. When the data changes, the content at the interpolation will not be updated
<span v-once>This will not change: {{ msg }}</span>
  • v-html: parse HTML and display
  • v-text: render the content text of the specified dom, which is similar to Mustache. It is generally not used and is not flexible enough. It will cover all the contents in the label
  • v-pre: display the label content intact without parsing
<h2 v-pre>{{message}} </h2>  

Result: {message}}

  • v-cloak: solve the problem of {}} flicker in vue parsing Caton
    Before vue parsing, div has the attribute v-cloak, which is not available after parsing.
    Therefore, you can use this instruction to hide the uncompiled Mustache tag until the instance is ready
  <div id="app" v-cloak>{{message}}</div>
  <style>
      [v-cloak]{ display:none; }
  </style>

2. Binding properties (dynamic properties)

v-bind is used to bind one or more attribute values or pass props values to another component. Abbreviated as colon:

1. src and href of element

<img :src="ImgUrl" />
<a :href="aHref">Baidu</a>

2. class binding

Object syntax

We can pass v-bind:class an object to dynamically switch classes

<div v-bind:class="{ active: isActive }"></div>

The above syntax indicates that the existence of the active class will depend on the data property isActive truthiness.
You can dynamically switch multiple classes by passing in more fields in the object. In addition, the v-bind:class instruction can also coexist with the ordinary class attribute.

<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
data: {
  isActive: true,
  hasError: false
}

The result is rendered as:

<div class="static active"></div>

When isActive or hasError changes, the class list will be updated accordingly. For example, if the value of hasError is true, the class list will change to "static active text danger".
The bound data object does not need to be defined inline in the template, but can also be defined in data

<div v-bind:class="classObject"></div>
data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}

The rendering result is the same as above. We can also bind a return object here Calculation properties.

<div v-bind:class="classObject"></div>
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

Method to return object

<div v-bind:class="IsActive()"></div>
data: {
  isActive: true,
  error: null
},
methods: {
  IsActive() {
    return {
      active: this.isActive && !this.error,
      line:isLine
    }
  }
}

Array syntax

We can pass an array to v-bind:class to apply a class list:

<div v-bind:class="[activeClass, errorClass]"></div>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

Render as:

<div class="active text-danger"></div>

You can switch class es in the list according to the conditions, and use ternary expressions:

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

This will always add errorClass, but only if isActive is true[ 1] activeClass is added only when.

However, it is cumbersome to write this when there are multiple conditional class es. Therefore, object syntax can also be used in array syntax:

<div v-bind:class="[{ active: isActive }, errorClass]"></div>

3. Style binding inline style

Object syntax
The object syntax of v-bind:style is very intuitive -- it looks very much like CSS, but it's actually a JavaScript object. CSS property names can be named with camel case or kebab case (remember to enclose them in quotation marks):

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> 
<!--The number plus string is implicitly converted to a string type -->
data: {
  activeColor: 'red',
  fontSize: 30
}

It's usually better to bind a style directly to an object:

<div v-bind:style="styleObject"></div>
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}

Similarly, object syntax is often used in conjunction with the calculated properties of the returned object. Or method

<div v-bind:class="classObject"></div> //Calculation properties
<div v-bind:class="classObject()"></div> //method

Array syntax

The array syntax of v-bind:style can apply multiple style objects to the same element:

<div v-bind:style="[baseStyles, overridingStyles]"></div>

3. Calculation properties

Putting too much logic into the template will make the template too heavy and difficult to maintain. The data needs to be changed and displayed

<div id="example">   {{ message.split('').reverse().join('') }} </div>

Basic example

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p> <!--Name the function according to the style of the attribute,The name of the referenced function does not need parentheses-->
</div>
<script>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // Calculate the getter of the property
    reversedMessage: function () {
      // `this ` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

result:

Original message: "Hello"

Computed reversed message: "olleH"

Here we declare a calculation property reversedMessage. The function we provide will be used as property VM getter function of reversedMessage:

console.log(vm.reversedMessage) // => 'olleH'
vm.message = 'Goodbye'
console.log(vm.reversedMessage) // => 'eybdooG'

You can open the browser console and modify the VM in the example by yourself. vm. The value of reversedmessage always depends on VM The value of message.
You can bind the calculation property in the template as you bind the ordinary property. Vue knows VM Reversedmessage depends on VM Message, so when VM When message changes, all dependent VMS The binding of reversedmessage will also be updated. And the best thing is that we have created this dependency declaratively: the getter function that calculates the attribute has no side effects, which makes it easier to test and understand.

Calculate the getter and setter of the property

The default calculation property is only getter, which is read-only. However, you can also provide a setter when necessary:

// ...
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}
// ...

Now run VM When fullname = 'john doe', setter will be called, VM Firstname and VM LastName will be updated accordingly.

Because there is generally no setter for calculated properties, it is abbreviated as

 fullName:  function () {
      return this.firstName + ' ' + this.lastName
 }

Calculate attribute vs method
The same result can be achieved by calling a method in an expression.

<p>Reversed message: "{{ reversedMessage() }}"</p>
// In component
<script>
methods: {
  reversedMessage: function () {
    return this.message.split('').reverse().join('')
  }
}
</script>

The final result of the two methods is exactly the same. However, the difference is that the calculated attributes are cached based on their responsive dependencies. They are re evaluated only when the relevant responsive dependencies change. This means that as long as the message has not changed, multiple accesses to the reversedMessage calculation property will immediately return the previous calculation result without executing the function again.
This also means that the following calculated properties will not be updated. In contrast, whenever a re rendering is triggered, the calling method will always execute the function again.

Calculate attribute vs listen attribute

Vue provides a more general way to observe and respond to data changes on Vue instances: listening properties.

<div id="demo">{{ fullName }}</div>
<script>
    var vm = new Vue({
        el: '#demo',
        data: {
            firstName: 'Foo',
            lastName: 'Bar',
            fullName: 'Foo Bar'
        },
        watch: {
            firstName: function (val) {
                this.fullName = val + ' ' + this.lastName
            },
            lastName: function (val) {
                this.fullName = this.firstName + ' ' + val
            }
        }
</script>

The above code is imperative and repetitive. Compare it with the version of the calculated attribute:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

Calculate attribute parameters

The calculation attribute itself cannot pass parameters, but parameters can be passed through closures, but there is no caching mechanism after passing parameters, which is no different from methods, so this is not introduced on the official website

 computed: {
	  usertype(){
		  return function (value){
			  var user = ''
			  value === 1 ? user = 'student' : user = 'teacher'
			  return user
		  }
	  }
  }

4. Event listening

Basics

You can use the v-on instruction to listen for DOM events and run some JavaScript code when triggered. Abbreviation @ click
Many event processing logic will be more complex, so v-on can also receive a method name to call

<div id="example-1">
    <button v-on:click="counter += 1">Add 1</button>
    <button v-on:click="increment"> + </button>
    <button v-on:click="decrement"> - </button>
    <p>The button above has been clicked {{ counter }} times.</p>
</div>
<script>
    var example1 = new Vue({
        el: '#example-1',
        data: {
            counter: 0
        },
      methods:{
        increment(){
          this.counter++
        },
        decrement(){
           this.counter--;
        }
      }
    })
</script>

Parameter problem (bracket problem)

1. No reference

<!--()not essential-->
<button v-on:click="greet">Greet</button>
<button v-on:click="greet()">Greet</button>

2. Have reference

<!--Method has parameters. No parameters are passed when calling, but they are added(),The formal parameter defaults to undefind-->
<button v-on:click="greet()">Greet</button> 
<!--Method has parameters. When calling, no parameters are passed or added(),Returns the generated by the browser Event object MouseEvent-->
<button v-on:click="greet">Greet</button> 

When only the event object is required,

<button @click="btnClick(event)">111</button>

When you need an event object and other objects, you can pass it into the method with the special variable $event:

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

Several wrong writing methods

<button @click="warn">111</button><!--The message is event and undefined-->
<button @click="warn("111",event)">111</button><!--The message is"111"and undefined(Error reported, not found event)-->

Event modifier

Calling event. in event handler Preventdefault() or event Stoppropagation () is a very common requirement. Although we can easily implement this in the method, a better way is that the method only has pure data logic, rather than dealing with DOM event details.

To solve this problem, Vue JS provides event modifiers for v-on. As mentioned earlier, modifiers are represented by the instruction suffix beginning with a dot.

<!-- Prevent click events from continuing to propagate -->
<a v-on:click.stop="doThis"></a>
  
<!-- Submitting an event no longer reloads the page -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- Disable page scrolling under mask-->
<a v-on:touchmove.stop.prevent="doThat"></a> 

<!-- Use event capture mode when adding event listeners -->
<!-- That is, events triggered by internal elements are processed here first, and then handed over to internal elements for processing -->
<div v-on:click.capture="doThis">...</div>

<!-- Only when event.target Is the handler function triggered when the current element itself -->
<!-- That is, the event is not triggered from an internal element -->
<div v-on:click.self="doThat">...</div>

<!-- Default behavior for scrolling events (Rolling behavior) Will be triggered immediately , Without waiting `onScroll` complete, This includes `event.preventDefault()` Situation -->
<div v-on:scroll.passive="onScroll">...</div>

1. Event modifier

  • . stop to prevent the event from bubbling and call event stopPropagation
<!-- Prevent click events from continuing to propagate --> 
<a v-on:click.stop="doThis"></a> 
  • . prevent prevents the default behavior of the event and calls event preventDefault()
<!-- Submitting an event no longer reloads the page -->
<form v-on:submit.prevent="onSubmit"></form> 
<!-- Modifiers can be concatenated -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- Disable page scrolling under mask-->
<a v-on:touchmove.stop.prevent="doThat"></a> 
<!-- Only modifiers -->
<form v-on:submit.prevent></form>
  • The callback is triggered only when the element itself bound to the. self event is triggered
<!-- Only when event.target Is the handler function triggered when the current element itself -->
<!-- That is, the event is not triggered from an internal element --> 
<div v-on:click.self="doThat">...</div>
  • The. Once event can only be triggered once, and will not be triggered the second time

Unlike other modifiers that work only on native DOM events The once modifier can also be used in custom Component events upper

  • . native turns a vue component into an ordinary html so that it can listen to click and other native events, and listen to the native events of the component
<Tag @click.native="handleClick">ok</Tag>
  • . passive can improve the performance of the mobile terminal.

No passive and Use with prevent because Prevent will be ignored and the browser may show you a warning. Remember passive will tell the browser that you don't want to block the default behavior of the event.

<!-- Default behavior for scrolling events (Rolling behavior) Will be triggered immediately -->
<!-- Without waiting `onScroll` complete  -->
<!-- This includes `event.preventDefault()` Situation -->
<div v-on:scroll.passive="onScroll">...</div>
  • .capture
<!-- Use event capture mode when adding event listeners --> 
<!-- That is, events triggered by internal elements are processed here first, and then handed over to internal elements for processing --> 
<div v-on:click.capture="doThis">...</div> 

When using modifiers, order is important; The corresponding code will be generated in the same order. Therefore, use v-on: click prevent. Self will block all clicks, while v-on: click self. Prevent only blocks clicks on the element itself.

No passive and Use with prevent because Prevent will be ignored and the browser may show you a warning. Remember passive will tell the browser that you don't want to block the default behavior of the event.

5. Conditional rendering

Basics

The v-if instruction is used to render a piece of content conditionally. This content will only be rendered when the expression of the instruction returns the truth value.

<h1 v-if="isShow">Vue is awesome!</h1>
<h1 v-else>isShow by false Time display</h1>

Use v-if conditional rendering groups on < template > elements

Because v-if is an instruction, it must be added to an element. But what if you want to switch multiple elements? At this point, you can treat a < template > element as an invisible wrap element and use v-if on it. The final render will not contain the < template > element.

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

v-else-if is not commonly used, and it is better to calculate attributes

<div v-if="type === 'A'">A</div>
<div v-else-if="type === 'B'"> B</div>
<div v-else-if="type === 'C'">  C</div>
<div v-else>  Not A/B/C</div>

Similar to v-else, v-else-if must also follow the element with v-if or v-else-if.

Manage reusable elements with key

Vue renders elements as efficiently as possible, often reusing existing elements rather than rendering from scratch. In addition to making Vue very fast, there are other benefits. For example, if you allow users to switch between different login methods:

<template v-if="loginType === 'username'">
  <label for="username">Username</label><!--click label,directive input Get focus-->
  <input id="username" placeholder="Enter your username">
</template>
<template v-else>
  <label for="email">Email</label>
  <input id="email" placeholder="Enter your email address">
</template>

Problem: switching loginType in the above code will not clear what the user has entered.

Reason: the two templates use the same elements. When rendering virtual DOM, for performance reasons, < input > will not be replaced, but only its placeholder,

Solution: add a key attribute with unique value. Different keys will not be reused

<template v-if="loginType === 'username'">
  <label>Username</label>
  <input placeholder="Enter your username" key="username-input">
</template>
<template v-else>
  <label>Email</label>
  <input placeholder="Enter your email address" key="email-input">
</template>

Note that the < label > elements will still be reused efficiently because they do not add a key attribute.

v-show

Another option for displaying elements based on conditions is the v-show instruction. The usage is roughly the same:

<h1 v-show="ok">Hello!</h1>

The difference is that elements with v-show are always rendered and retained in the DOM. V-show simply switches the CSS attribute display of an element.

Note that v-show does not support < template > elements or v-else.

v-if vs v-show

v-if is a "real" conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during switching.

v-if is also lazy: if the condition is false at the initial rendering, nothing is done -- the conditional block does not start rendering until the condition first becomes true.

In contrast, v-show is much simpler - no matter what the initial condition is, the element will always be rendered, and it is simply switched based on CSS. When the condition is false, it is just to set the display attribute of the element to none.

Generally speaking, if show has higher initial rendering overhead.

Therefore, if you need to switch very frequently, it is better to use v-show; If the conditions rarely change at run time, it is better to use v-if.

Using both v-if and v-for is not recommended. When v-if is used with v-for, v-for has a higher priority than v-if.

6. List rendering

6.1 traversal array

Use v-for to correspond an array to a group of elements. The v-for instruction needs to use the special syntax in the form of item in items, where items is the source data array and item is the alias of the iterated array elements.

<ul id="example-1">
  <li v-for="item in items" :key="item.message">{{ item.message }}  </li>
</ul>
<script>
var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})
</script>

result:

  • Foo
  • Bar

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

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

result:

  • Parent - 0 - Foo
  • Parent - 1 - Bar

You can also use of instead of in as the separator, because it is closer to the syntax of JavaScript iterators:

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

6.2 traversal object

You can also use v-for to traverse the properties of an object.

<!--The first parameter is value-->
<ul id="v-for-object" class="demo">
  <li v-for="value in object"> {{ value }} </li>
</ul>
<!--The second parameter is the key name key-->
<div v-for="(value, name) in object">
  {{ name }}: {{ value }}
</div>
<!--The third parameter is the index index-->
<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>

<script>
new Vue({
  el: '#v-for-object',
  data: {
    object: {
      title: 'How to do lists in Vue',
      author: 'Jane Doe',
      publishedAt: '2016-04-10'
    }
  }
})
</script>

result:

  • How to do lists in Vue

  • Jane Doe

  • 2016-04-10

title: How to do lists in Vue

author: Jane Doe

publishedAt: 2016-04-10

\0. title: How to do lists in Vue

\1. author: Jane Doe

\2. publishedAt: 2016-04-10

When traversing an object, press object The results of keys () are traversed, but there is no guarantee that its results are consistent under different JavaScript engines.

6.3 maintenance status (key attribute)

When Vue is updating the list of elements rendered using v-for, it defaults to the update in place policy. If the order of data items is changed, Vue will not move DOM elements to match the order of data items, but update each element in place and ensure that they are rendered correctly at each index position (related to virtual Dom and Diff algorithm).

This default mode is efficient, but only applies to list rendered output that does not depend on subcomponent state or temporary DOM state (e.g. form input value).

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

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

It is recommended to provide key attribute when using v-for as much as possible, unless it is very simple to traverse the output DOM content, or deliberately rely on the default behavior to improve performance. Because it is a general mechanism for Vue to identify nodes, key is not specifically associated with v-for.

Do not use non basic type values such as objects or arrays as v-for key s. Instead, use string or numeric type values.

6.4 array update detection

Change method (which methods of the array are responsive)

Changing methods changes the original array that called them

Vue wraps the change method of the array being listened on, so they will also trigger view updates. These wrapped methods include:

  • push() plus element, this names. push("aaa","bbb")

  • Pop() deletes the last element of the array, names pop()

  • shift() deletes the first element of the array

  • unshift() adds an element to the front of the array

  • Insert / replace element

    The first parameter is where to start deleting / inserting / replacing elements

    Delete element: the second parameter is passed in to delete several elements. If it is not passed in, all the following elements will be deleted: splice(0,2)

    Replace element: the second element passes in several elements to be replaced, followed by the element splice used for replacement (0,2,'d ',' 2 ')

    Insert element: the second element passes in 0, followed by the element splice to be inserted (0,0,'d ')

  • sort() array sort

  • reverse() flip array

Replace array (higher-order functions filter, map, reduce)

Non changing methods, such as filter(), concat(), and slice(). They do not change the original array, but always return a new array. You might think this will cause Vue to discard the existing Dom and re render the entire list. Fortunately, this is not the case. Vue implements some intelligent heuristic methods to maximize the reuse of DOM elements, so it is very efficient to replace the original array with an array containing the same elements.

Due to JavaScript limitations, Vue cannot detect changes in arrays and objects. Deep response principle There are relevant discussions in.

filter() displays the filtered / sorted results

The callback function must return a boolean value:

When true is returned, the n of this callback will be automatically added to the new array inside the function; When false is returned, the internal function will filter out this n.

Sometimes we want to display the 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 the filtered or sorted array. For example:

<li v-for="n in evenNumbers">{{ n }}</li>
<script>
data: {
  numbers: [ 1, 2, 3, 4, 5 ]
},
computed: {
  evenNumbers: function () {
    return this.numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}
</script>

When the calculated attribute is not applicable (for example, in a nested v-for loop), you can use one method:

<ul v-for="set in sets">
  <li v-for="n in even(set)">{{ n }}</li>
</ul>
<script>
data: {
  sets: [[ 1, 2, 3, 4, 5 ], [6, 7, 8, 9, 10]]
},
methods: {
  even: function (numbers) {
    return numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}
</script>

map() mapping

let nums=[ 1, 2, 3, 4, 5 ]
let nuwnums=nums.map(function(n){
    return n*2
})

Summary of elements in reduce array

let nums=[ 1, 2, 3, 4, 5 ]
//preValue is the previous value, and 0 is the initial default value; n is the element in the array
let nuwnums=nums.reduce(function(preValue,n){
    return preValue+n
},0)

[use value range in v-for]

v-for can also accept integers. In this case, it repeats the template the corresponding number of times.

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

result:

1 2 3 4 5 6 7 8 9 10

Use v-for on < template >

Similar to v-if, you can also use < template > with v-for to loop render a piece of content containing multiple elements. For example:

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

Use v-for with v-if

Note that we do not recommend using v-if and v-for on the same element.

When they are on the same node, v-for has a higher priority than v-if, which means that v-if will run repeatedly in each v-for loop.

7. Form input binding v-model

Basic use

Realize the bidirectional binding of form elements and data

<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
data:{
	message:''
}

principle

<input type="text" :value="message" @input="valueChange" />
<p>Message is: {{ message }}</p>
<script>
  data:{
    message:''
  },
	methods:{
     valueChange(event){
       this.message=$event.target.value;
     }
  }      
</script>

Abbreviation:

<input type="text" :value="message" @input="message=$event.target.value" >

v-model internally uses different properties for different input elements and throws different events:

  • text and textarea elements use value property and input events;
  • checkbox and radio use checked property and change events;
  • The select field takes value as a prop and change as an event.

Radio radio box

<label for="male">
	<input type="radio" id="male" value="male" v-model="sex">male
</label>
<label for="female">
	<input type="radio" id="female" value="female" v-model="sex">female
</label>
<h2>What gender do you choose{{sex}}</h2>

data:{sex:'female'}

sex in data is the default value, and its radio button will also be selected by default because of bidirectional binding

Mutually exclusive radio buttons: v-model or name = "sex" are placed in a group

checkbox check box

Single check box, bound to Boolean value

<label for="agree">
	<input type="checkbox" id="agree" v-model="isAgree">Consent agreement
</label>
<h2>Do you agree to the agreement{{isAgree}}</h2>
<button :disabeled="!isAgree">
  next step
</button>
data:{isAgree:false}

Multiple selection boxes, bound to arrays

<input type="checkbox"  v-model="hobbies">Basketball
<input type="checkbox"  v-model="hobbies">Football
data:{hobbies:[]}

select selection box

Single choice

<select v-model="fruit">
  <option value="apple">Apple</option>
  <option value="bannner">Banana</option>
</select>
<h2>The fruit of choice is{{fruit}}</h2>
data:{fruit:''}

Multiple choice

<select v-model="fruits" multiple>
  <option value="apple">Apple</option>
  <option value="bannner">Banana</option>
</select>
<h2>The fruit of choice is{{fruits}}</h2>
data:{fruits:[]}

Modifier

. lazy update the view after entering the content in the input box and the cursor leaves
. trim filter leading and trailing spaces
. number automatically converts the user's input value to numeric type. If you enter numbers first, it will restrict you to enter only numbers; If you don't input a string first, it's equivalent to adding a string first number

The usage is as follows:

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

There are also many modifiers, such as keyboard, mouse and so on

Keywords: Vue

Added by ckehrer on Thu, 10 Feb 2022 23:41:24 +0200