• This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Vue related commands

  • A feature with special meaning and function
  • Instructions are prefixed with a V – to indicate that they are special features provided by Vue
  • Directives can use data directly from data

v-pre

  • Skip the compilation of this element and its children. You can use it to display the original Mustache tag. Skipping a large number of nodes without instructions speeds up compilation.

    <! <span v-pre>{{MSG}}</span>Copy the code

v-cloak

  • This instruction remains on the element until the associated instance is finished compiling

  • Can solve the flicker problem

  • Used with CSS rules such as [V-cloak] {display: None}, this instruction can hide uncompiled Mustache tags until the instance is ready

    [v-cloak] {
      display: none;
    }
    Copy the code
    <! -- {{message}} will not be displayed until completion of compilation --> <div v-cloak> {{message}} </div>Copy the code

v-once

  • Only render elements once. On subsequent re-rendering, the element and all its children are treated as static and skipped. This can be used to optimize update performance

    <! <span v-once>{{MSG}}</span> <! - a child element -- -- > < div v - once > < h1 > comment < / h1 > < p > {{MSG}} < / p > < / div >Copy the code

v-text

  • Update the textContent of the element

    <span v-text="msg"></span> <! <span>{{MSG}}</span>Copy the code

v-text VS Mustache

  • While V-text replaces all text in the element, Mustache replaces only himself without empting the element’s content

    <! - rendering as: < span > shanshan is the most beautiful < / span > -- > < span v - text = "MSG" > - < / span > <! - rendering as: < span > - very best - < / span > -- > < span > - {{MSG}} - < / span >Copy the code
  • V-text priority higher than {{}}

textContent VS innerText

  1. When text substitution is set, all children of the specified node are also replaced.
  2. TextContent gets the contents of all elements, including<script> 和 <style>Element, whereas innerText does not.
  3. InnerText is influenced by CSS styles and does not return the text of the hidden element, whereas textContent does.
  4. Because the innerText is affected by CSS styles, it triggers reflow, but the textContent does not.
  5. InnerText is not a standards-specified API, but is introduced by IE, making it more IE friendly. TextContent, though standard, is only supported in IE8+ and older browsers, and both are available in the latest browsers.
  6. To sum up, Vue uses textContent from a performance perspective.

Test the innerText and textContent performance

<ul class="list"> <li>1</li> <! <li>1000</li> </ul>Copy the code
const oList = document.getElementById("list");

console.time("innerText");
for(let i = 0; i < oList.childElementCount; i++){
  ul.children[i].innerText="innerText";
}
console.timeEnd("innerText");

console.time("textContent");
for(let i = 0; i < oList.childElementCount; i++){
  ul.children[i].textContent="innerText";
}
console.timeEnd("textContent");
Copy the code

v-html

  • Updates the innerHTML of the element

  • Note: The content is inserted as normal HTML and will not be compiled as a Vue template

  • Dynamically rendering arbitrary HTML on a website is very dangerous because it is prone to XSS attacks. Use V-HTML only for trusted content, never for user-submitted content.

    < input type = "text" / > < button > click < / button > < div id = "app" > < div v - HTML = "MSG" > < / div > < / div >Copy the code
    const vm = new Vue({
      el: '#app',
      data: {
        msg: 'hello world'
      }
    })
    
    const oInput = document.getElementsByTagName('input')[0];
    const oButton = document.getElementsByTagName('button')[0];
    let msg = null;
    oButton.onclick = function () {
      vm.msg = oInput.value;
    }
    Copy the code

Conditions apply colours to a drawing

v-if

  • Used to conditionally render a piece of content. This content will only be rendered if the expression of the directive returns truthy.

Switching between multiple elements

  • Because v-if is an instruction, it must be added to one element, but what if you want to switch multiple elements? You can treat a

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

v-else

  • Add “else block” for V-if or V-else -if.

  • Note: The previous sibling element must have v-if or V-else -if

    <div v-if=" math.random () > 0.5"> </div>Copy the code

v-else-if

  • “Else if block” for V-if. You can call it chained.

  • Note: The previous sibling element must have v-if or V-else -if

    <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>
    Copy the code

v-show

  • Toggles the element’s display CSS property based on the expression’s true or false value.

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

v-if VS v-show

  1. V-if is lazy and does nothing if the condition is false during the initial rendering, until the condition is true for the first time and the conditional block is rendered. With V-show, elements are always rendered regardless of initial conditions and are simply switched based on CSS.
  2. V-if has a higher switching overhead, V-show has a higher initial rendering overhead, v-show is better if you need to switch very frequently, and v-if is better if conditions change very little at run time
  3. V – show does not support<template>The element
  4. V-show does not support V-else/V-else -if

V – the bind command

  • Dynamically bind one or more features

  • : Indicates the passed parameter

    <! <img v-bind: SRC ="imageSrc"> <! - the dynamic characteristics of server (+) - - > < button v - bind: [key] = "value" > < / button > <! <img: SRC ="imageSrc"> <! -- the dynamic characteristics of server (+) - - > < button: [key] = "value" > < / button > <! Inline string concatenation - - - > < img: SRC = "'/path/to/images / + fileName" >Copy the code
  • With no arguments, you can bind to an object that contains key-value pairs. Note that the class and style bindings do not support arrays and objects at this time.

    <! <div v-bind="{id: someProp, 'other-attr': otherProp}"></div>Copy the code
  • Because string concatenation is cumbersome and error-prone, Vue has enhanced it when binding class or style features to allow expressions to be arrays or objects in addition to strings.

    • The binding class

      • Object syntax

        <div v-bind:class="{ red: isRed }"></div>
        Copy the code

        The syntax above indicates that the existence of the active class depends on whether the data attribute isActive is true or false.

      • Array syntax We can apply a class list by passing an array to V-bind :class

        <div v-bind:class="[classA, classB]"></div>
        Copy the code
      • In array syntax you can always switch classes using ternary expressions

        <div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
        Copy the code
      • You can use object syntax in array syntax

          <div v-bind:class="[classA, { classB: isB, classC: isC }]">
          <div v-bind:class="classA" class="red">
        Copy the code
      • V-bind: Classes can coexist with regular classes

          <div v-bind:class="classA" class="red">
        Copy the code
    • The binding style

      • Using object syntax looks a lot like CSS, but it’s actually a JavaScript object and the CSS property names can be camelCase or kebab-case but if you’re using a kebab-case, you’re going to put it in quotes

        <div v-bind:style="{ fontSize: size + 'px' }"></div>
        Copy the code
        data: {
          size: 30
        }
        Copy the code

        You can also bind a style object directly to make the template clearer:

        <div v-bind:style="styleObject"></div>
        Copy the code
        data: {
          styleObject: {
            fontSize: '13px'
          }
        }
        Copy the code
      • Using array syntax Array syntax allows you to apply multiple style objects to the same element

        <div v-bind:style="[styleObjectA, styleObjectB]"></div>
        Copy the code
      • Automatically prefix binding style. CSS properties that require a browser engine prefix, such as transform, vue.js, will automatically detect and add the corresponding prefix.

      • Multiple Values Since 2.3.0 you can provide an array of multiple values for a property in the style binding, often used to provide multiple prefixed values:

        <div v-bind:style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
        Copy the code

        This only renders the last value in the array that is supported by the browser. In this case, if the browser supports flexbox without the browser prefix, only display: flex will be rendered.

  • Abbreviations: :

  • Modifier: Modifier is a special suffix specified by the period. Used to indicate that an instruction should be bound in a particular way.

    • .camel converts uppercase letters to lowercase letters due to the binding feature, such as:

      <! < SVG: viewbox="0 0 100 100"></ SVG ></ SVG >Copy the code

      Therefore, Vue provides the V-bind modifier Camel, which allows the v-bind attribute names to be humped when using DOM templates, such as the viewBox attribute of SVG

      <svg :view-box.camel="viewBox"></svg>
      Copy the code
    • .prop is used to bind DOM properties.

      <div v-bind:text-content.prop="text"></div>
      Copy the code
    • Sync will explain the components

V – on command

  • The V-ON directive listens for DOM events and runs some JavaScript code when triggered

  • The event type is specified by the parameter

    <div id="app"> <button V-on :click="counter += 1"> </p>Copy the code
    const vm = new Vue({
      el: 'app',
      data: {
        counter: 0
      }
    })
    Copy the code
  • But much of the event-handling logic is very complex, so it’s not feasible to write JavaScript code directly into v-ON instructions. So V-ON can also receive a method name that needs to be called.

    <div id="app"> <! <button V-on :click="addCounter"> </button> <p> </div>Copy the code
    Const vm = new Vue({el: '#app', data: {counter: 0}, // define methods in methods: {addCounter: Function (e) {this.counter += 1; // e is the native DOM event cosnole.log(e.target); }}})Copy the code
  • Methods also delegate directly to Vue instance objects, so they can be run directly:

      vm.addCounter();
    Copy the code
  • 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="addCounter(5)"> </p> <div >Copy the code
    new Vue({ el: '#app', data: { counter: 0 }, methods: { addCounter: function (num) { this.counter += 5; }}})Copy the code
  • When you use event objects in associative sentences, you can use the special variable $event:

    <div id="app"> <button V-on :click="addCounter(5, $event)"> </p>Copy the code
    new Vue({
      el: '#app',
      methods: {
        addCounter: function (num, e) {
          this.counter += 5;
          cosnole.log(e.target);        
        }
      }
    })
    Copy the code
  • Dynamic events can be bound. Vue version requires 2.6.0+

    <div v-on:[event]="handleClick"> </div>Copy the code
    const vm = new Vue({ el: '#app', data: { event: 'click' }, methods: { handleClick () { alert(1); }}})Copy the code
  • It is possible to bind an object without arguments. Vue version requires 2.4.0+.

    • {event name: event execution function}
    • Function pass-arguments & modifiers are not supported using this method
    <div v-on="{ mousedown: doThis, mouseup: doThat }"></div>
    Copy the code
  • Short for the V-ON command: @

Why listen for events in HTML?

  1. A glance at an HTML template makes it easy to locate the corresponding method in JavaScript code.
  2. Because you don’t have to manually bind events in JavaScript, your ViewModel code can be very logical and completely decoupled from DOM, making it easier to test
  3. When a ViewModel is destroyed, all event handlers are removed. Don’t you have to worry about cleaning them up

The last

If it is helpful to you, I hope I can give 👍 comment collection three even!

Bloggers are honest and answer questions for free ❤

Welcome to discuss in the comments section, the excavation officials will draw 100 nuggets in the comments section after the end of the Excavation project activity, see the details of the lucky draw in the event article, friends to discuss!!