Syntax

05 Feb 2024 . vue .

v-for

key

In order to track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item with in v-for iteration. An ideal value for key would be the unique id of each item.

<ul>
        <li v-for="item in letters" :key="item"></li>
</ul>

When key is not added, the rendering will be replaced in order. If you add key, you will directly place it in the specified position, and improve efficiency.

v-model

modifiers

1. lazy: By default, v-model syncs the input with the data after each input event. You can add the lazy modifier to instead sync after change events.

<!-- synced after "change" instead of "input" -->
<input v-model.lazy="msg" >

2. number: If you want user input to be automatically typecast as a number, you can add the number modifier to your v-model. Even with type=”number”, the value of HTML input elements always returns a string. So, this typecast modifier is required.

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

3. trim: If you want whitespace from user input to be trimmed automatically, you can add the trim modifier to your v-model.

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

custom directive

Custom Directives are tiny commands that you can attach to DOM elements. They are prefixed with v- to let the library know you’re using a special bit of markup and to keep syntax consistent. They are typically useful if you need low-level access to an HTML element to control a bit of behavior.

// Register a global custom directive called `v-focus`
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})

<input v-focus>

hook functions

  1. bind: This occurs once the directive is attached to the element.
  2. inserted: This hook occurs once the element is inserted into the parent DOM.
  3. update: This hook is called when the element updates, but children haven’t been updated yet.
  4. componentUpdated: This hook is called once the component and the children have been updated.
  5. unbind: This hook is called only once when the directive is removed.