D7.VUE basic learning 20211231

Posted by zero-one on Mon, 03 Jan 2022 23:22:13 +0100

V conditional rendering

5.1 v-if

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

<h1 v-if="awesome">Vue is awesome!</h1>

You can also add an else block with v-else:

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
Using v-if conditional rendering groups on elements

You can treat an element as an invisible wrap element and use v-if on it. The final render will contain no elements.

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

5.1.1 v-else

You can use the v-else instruction to represent the "else block" of v-if:

<div v-if="Math.random() > 0.5">
  Now you see me
</div>
<div v-else>
  Now you don't
</div>

The v-else element must follow the element with v-if or v-else-if, otherwise it will not be recognized

5.1.2 v-else-if

As the name suggests, it acts as an "else if block" of v-if, which can be used continuously:

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

5.1. 3 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>Username</label>
  <input placeholder="Enter your username">
</template>
<template v-else>
  <label>Email</label>
  <input placeholder="Enter your email address">
</template>

Then in the above code, switching loginType will not clear the content entered by the user, because the two templates use the same element and will not be replaced - just its placeholder.
input placeholder displays prompt text in the text box and disappears after losing focus

If you don't want the contents of the input box to remain unchanged

This is not always in line with the actual needs, so Vue provides you with a way to express "these two elements are completely independent, don't reuse them". Just add a key attribute with unique value:

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

Now, each time you switch, the input box will be re rendered.

Note that elements are still reused efficiently because they do not add a key attribute.

5.2 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 elements or v-else.

5.3 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 conditions are, elements are always rendered and simply switched based on CSS.
In other words, v-show will render labels in DMO at the beginning, but whether to display them depends on the value of v-show

Generally speaking, v-if has higher switching overhead, while v-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.

5.4 use of V-IF with v-for

Using both v-if and v-for is not recommended. Please refer to the style guide for more information.

When v-if is used with v-for, v-for has a higher priority than v-if. Consult the list rendering guide for details.

Vi List rendering

6.1 use v-for to correspond an array to a group of elements

Render a list based on an array with the v-for instruction. The v-for instruction requires a special syntax in the form of item in items, where items is the source data array and item is the alias of the array element being iterated.

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

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>
var example2 = new Vue({
  el: '#example-2',
  data: {
    parentMessage: 'Parent',
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})

result:

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

You can 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 using objects in v-for

Use v-for to traverse the properties of an object.

<ul id="v-for-object" class="demo">
  <li v-for="value in object">
    {{ value }}
  </li>
</ul>
new Vue({
  el: '#v-for-object',
  data: {
    object: {
      title: 'How to do lists in Vue',
      author: 'Jane Doe',
      publishedAt: '2016-04-10'
    }
  }

result:

  • How to do lists in Vue
  • Jane Doe
  • 2016-04-10
The second parameter that can be provided is the property name (that is, the key name)
<div v-for="(value, name) in object">
  {{ name }}: {{ value }}
</div>

title: How to do lists in Vue
author: Jane Doe
publishedAt: 2016-04-10

You can use the third parameter as an index
<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>

0.title: How to do lists in Vue
1.author: Jane Doe
2.publishedAt: 2016-04-10

6.3 maintenance status

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.

This default mode is efficient, but only applies to list rendered output that does not depend on subcomponent state or temporary DOM state (for example, 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. As we will see later in the guide, it has other uses.

Do not use non basic type values such as objects or arrays as v-for key s. Use a value of type string or numeric.

For more details on the usage of key attribute, please move to the API document of key.

6.4 array update detection

6.4. 1 mutation method

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

  • push() # can accept any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
  • pop() # removes the last item at the end of the array, reduces the length value of the array, and then returns the removed item.
  • shift() # deletes the first item of the original array and returns the value of the deleted element; If the array is empty, undefined is returned.
  • unshift() # adds a parameter to the beginning of the original array and returns the length of the array.
  • splice() # is a powerful array method. It has many uses and can be used to delete, insert and replace
  • sort() # sorts the array items in ascending order -- that is, the smallest value comes first and the largest value comes last.
  • reverse() # reverses the order of array items.
    Calling the above method updates the array and also triggers the view update
    You can open the console and try to call the mutation method on the items array in the previous example. For example, example1 items. push({ message: 'Baz' })

6.4. 2 replace array

Mutation methods, as the name suggests, change the original array that calls these methods. In contrast, there are non mutating methods, such as filter(), concat(), and slice(). They do not change the original array, but always return a new array. When using the non mutation method, you can replace the old array with the new array:

example1.items = example1.items.filter(function (item) {
  return item.message.match(/Foo/)
})

You might think that 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.

VII event processing

7.1 monitoring events v-on

Listen for DOM events and run some JavaScript code when triggered

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

7.2 event handling method

However, many event processing logic will be more complex, so it is not feasible to write JavaScript code directly in v-on instructions. Therefore, v-on can also receive a method name that needs to be called.

<div id="example-2">
  <!-- `greet` Is the method name defined below -->
  <button v-on:click="greet">Greet</button>
</div>
<script>
var example2 = new Vue({
  el: '#example-2',
  data: {
    name: 'Vue.js'
  },
  // Define methods in the 'methods' object
  methods: {
    greet: function (event) {
      // `this ` points to the current Vue instance in the method
      alert('Hello ' + this.name + '!')
      // `Event ` is a native DOM event
      if (event) {
        alert(event.target.tagName)
      }
    }
  }
})
</script>

7.3 methods in inline processor

In addition to being directly bound to a method, you can also call the method in the inline JavaScript statement:

<div id="example-3">
  <button v-on:click="say('hi')">Say hi</button>
  <button v-on:click="say('what')">Say what</button>
</div>
new Vue({
  el: '#example-3',
  methods: {
    say: function (message) {
      alert(message)
    }
  }
})

Sometimes you need to access the original DOM event in the inline statement processor. You can pass it into the method with the special variable $event:

<button v-on:click="warn('Form cannot be submitted yet.', $event)">
  Submit
</button>
<script>
 var vm =new Vue({
     el: '#example-3',
   methods: {
     warn: function (message, event) {
       // Now we can access the native event object
       if (event) {
         event.preventDefault()
       }
       alert(message)
     }
   }
   })
</script>
Original DOM event

click when the user clicks the mouse
When the web page is loaded
When the picture is loaded
When the mouse moves over an element
When the input field is changed
When an HTML form is submitted
When the user triggers the key

7.4 event modifiers

Calling event. in event handler Preventdefault() or event Stoppropagation () is a very common requirement. Although we can easily implement this in methods, a better way is that methods only have 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.

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

<!-- Submitting events no longer reloads 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>

<!-- 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 that is triggered when the current element itself -->
<!-- That is, the event is not triggered from an internal element -->
<div v-on:click.self="doThat">...</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, and v-on: click self. Prevent only blocks clicks on the element itself.

####### .once

<!-- The click event will only be triggered once -->
<a v-on:click.once="doThis"></a>

Unlike other modifiers that work only on native DOM events The once modifier can also be used on custom component events.

#######Vue also provides for the passive option in the addEventListener Passive modifier

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

This The passive modifier can especially improve the performance of the mobile terminal.

Don't take it 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.

7.5 key modifiers

When listening for keyboard events, we often need to check the detailed keys. Vue allows you to add key modifiers for v-on when listening for keyboard events:

<!-- Only in `key` yes `Enter` Time call `vm.submit()` -->
<input v-on:keyup.enter="submit">

You can directly add keyboardevent Any valid key name exposed by key is converted to kebab case as a modifier.

<input v-on:keyup.page-down="onPageDown">

In the above example, the handler will only be in $event Called when key equals PageDown.

Key code

The event usage of keyCode has been deprecated and may not be supported by the latest browsers.

7.6 system modifier keys

The following modifiers can be used to implement a listener that triggers mouse or keyboard events only when the corresponding key is pressed.

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

Note: on the Mac keyboard, meta corresponds to the command key (⌘). On the Windows system, the keyboard meta corresponds to Windows
Logo key (⊞). On the Sun operating system keyboard, meta corresponds to the solid gem key (◆). On other specific keyboards, especially MIT and Lisp
The keyboard of the machine and its subsequent products, such as Knight keyboard and space cadet keyboard, META is marked as "META". In symbols
On the keyboard, meta is marked as "meta" or "meta".

For example:

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

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

Note that the modifier key is different from the conventional key. When used with the keyup event, the modifier key must be pressed when the event is triggered. In other words, keyup can only be triggered by releasing other keys while pressing Ctrl ctrl. Releasing Ctrl alone will not trigger an event. If you want this behavior, please replace Ctrl with keyCode: keyup 17.

. exact modifier

. The exact modifier allows you to control events triggered by a precise combination of system modifiers.

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

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

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

Mouse button modifier

  • .left
  • .right
  • .middle
    These modifiers restrict the handler to respond only to specific mouse buttons.

Why listen for events in HTML

You may notice that this way of event monitoring violates the long-standing fine tradition of separation of concern. But don't worry, because all Vue JS event handling methods and expressions are strictly bound to the ViewModel of the current view, which will not lead to any maintenance difficulties. In fact, using v-on has several benefits:

1. You can easily locate the corresponding method in JavaScript code by glancing at the HTML template.

2. Because you don't need to bind events manually in JavaScript, your ViewModel code can be very pure logic, completely decoupled from DOM and easier to test.

3. When a ViewModel is destroyed, all event handlers will be deleted automatically. You don't have to worry about how to clean them up.

VIII Form input binding

8.1 basic usage

You can use the v-model instruction to create two-way data bindings on forms, and elements
It automatically selects the correct method to update the element according to the control type. Although some magic, v-model is essentially just a syntax sugar. It is responsible for monitoring user input events to update data, and some special processing for some extreme scenarios.

v-model will ignore the initial values of value, checked and selected attribute s of all form elements, and always take the data of Vue instances as the data source. You should declare the initial value in the data option of the component through JavaScript.

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

  • text and textarea elements use value attribute and input event;
    • vulue property: sets or returns the value of the value property of the text field.
    • input event: oninput event is triggered when the user inputs. It is triggered immediately when the element value changes;
      This event is triggered when the value of a or element changes
  • checkbox and radio use the checked attribute and change event;
    • checked property: you can set or return whether a radio button is selected.
    • change event: this event is triggered when the content of a form element changes
  • The select field takes value as a prop and change as an event.

give an example

1. Text
<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>

Multiline text

<span>Multiline message is:</span>
<p style="white-space: pre-line;">{{ message }}</p>
<br>
<textarea v-model="message" placeholder="add multiple lines"></textarea>

Interpolation ({text}}) in the text area does not take effect. Instead, v-model should be used.

2. Check box

Single check box, bound to Boolean:

<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{ checked }}</label><!--for Attribute specification label Which form element to bind to.-->

Multiple check boxes bound to the same array:

<div id='example-3'>
  <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>
<script>
new Vue({
  el: '#example-3',
  data: {
    checkedNames: []//Note to declare the initial value of v-model
  }
})
</script>
3. Radio button
<div id="example-4">
  <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>
<script>
var vm = new Vue({
      el: '#example-4',
      data: {
        picked: ''
      }
    })
</script>
4. Selection box
<div id="example-5">
  <select v-model="selected">
    <option disabled value="">Please select</option><!--disabled Property specifies that the drop-down list is disabled.
    										The disabled drop-down list is neither available nor clickable-->
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
  <span>Selected: {{ selected }}</span>
</div>
<script>
var vm = new Vue({
      el: '...',
      data: {
        selected: ''
      }
    })
</script>

Selected:

If the initial value of the v-model expression does not match any options, the element is rendered as "unchecked". In iOS, this prevents the user from selecting the first option. Because in this case, iOS will not trigger the change event. Therefore, it is more recommended to provide a disabled option with a null value as above

When multiple selections are made (bound to an array):

<div id="example-6">
  <select v-model="selected" multiple style="width: 50px;">
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
  <br>
  <span>Selected: {{ selected }}</span>
</div>
<script>
var vm = new Vue({
      el: '#example-6',
      data: {
        selected: []
      }
    })
</script>
5. 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>
<script>
var vm =new Vue({
      el: '...',
      data: {
        selected: 'A',
        options: [
          { text: 'One', value: 'A' },
          { text: 'Two', value: 'B' },
          { text: 'Three', value: 'C' }
        ]
      }
    })
</script>

8.2 value binding

For the options of radio buttons, check boxes and selection boxes, the value bound by v-model is usually a static string (for check boxes, it can also be Boolean):

<!-- When selected,`picked` As string "a" -->
<input type="radio" v-model="picked" value="a">

<!-- `toggle` by true or false -->
<input type="checkbox" v-model="toggle">

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

However, sometimes we may want to bind the value to a dynamic attribute of the Vue instance, which can be implemented with v-bind, and the value of this attribute can not be a string.

8.2.1 check box

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

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

8.2.2 radio buttons

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

Note that you need to declare pick in data

8.2.3 options in the selection box

<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

8.3 modifiers

8.3.1 .lazy

By default, the v-model is triggered at each input event (oninput event is triggered at user input.) After triggering, synchronize the value of the input box with the data (except when combining text with the above input method). You can add the lazy modifier to change to use the change event (1. The event will occur when the content of the domain changes; 2. The event can also be used for the event triggered after the radio box and check box change):

<!-- In“ change"Sometimes not“ input"Update when -->
<input v-model.lazy="msg" >
<!--Update when form changes,Instead of updating as you enter-->
<!--When changes occur,Loss of focus,When entering,When the input box becomes the focus,If you click-->

8.3.2 .number

If you want to automatically convert the user's input value to a numeric type, you can add the number modifier to the v-model:

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

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

8.3.3 .trim

If you want to automatically filter the first and last white space characters entered by the user, you can add the trim modifier to the v-model:

<input v-model.trim="msg">

Topics: Javascript Front-end Vue.js