Vue instruction Encyclopedia (super detailed)

Time:2021-6-8

This paper introduces the usage of various Vue instructions and the comparison between some of them

The outline of this paper: This paper will introduce the following Vue instructions and their syntax, usage, as well as the detailed comparison between the instructions
v-text,v-html,v-if,v-else,v-else-if,v-show,v-for,v-on,v-bind、v-model,v-pre,v-cloak,v-once


Interpolation expression (leading to instruction)

  1. The most common form of data binding is"Mustache" Grammar (double braces)Text interpolation of,MustacheThe label will be replaced by the value of the property on the corresponding data object. As long as the properties of the bound data object change, the content of the interpolation will be updated.
  2. Used itvueAll my friends know that,messageIs to parse data into plain text, that is to say, even ifmessageIt containshtmlTags, which are only regarded as plain text, cannot output real HTML.
  3. For example:
    <div id="app">
         <p>{{message}}</p>
     </div>
     <script type="text/javascript">
        var app = new Vue({
            el: '#app',
            data: {
                message: '<h1>asc</h1>'
            }
        })
    </script>
    <!-- The page is displayed as: < H1 > ASC < / H1 > -- >

v-text

  1. v-textIntroduction:
    • v-textThe same thing about interpolation expressions is that they also parse data into plain text (Interpreting HTML tags can lead to errors)XSS attack
    • But the difference between it and curly braces is: usev-textIt is not displayed when the page is loaded‘message’It solves the problem of interpolation expression flicker, because it is an attribute rather than an interpolation expression
  2. For example:
    <div id="app">
         The content here will be replaced</p>
     </div>
     <script>
        var vm = new Vue({
            el: "#app",
            data: {
                msg: "Hello! <h1>v-text</h1>",
            }
        })
     </script>
     <!-- The page is displayed as: Hello< h1>v-text</h1>-->
  3. Note: “page flicker” means that when the interpolation expression is loaded, it will be displayed directly on the page first‘message’And then compile the corresponding data

v-html

  1. Introduction: in order to output real HTML, you can use the v-html instruction. It is equivalent to the innerHTML attribute of JS and will parse the data into HTML.
  2. For example:
    <div id="app">
         The content here will be replaced</p>
     </div>
     <script>
        var vm = new Vue({
            el: "#app",
            data: {
                msg: "Hello! <h1>v-html</h1>",
            }
        })
     </script>
     <!-- The page is displayed as: Hello! v-html -->

v-if

  1. Introduction:v-ifInstructions forConditionally renderingA piece of content. This will only be returned in the expression of the instructiontruthyValue is rendered.
  2. For example:
    <div id="app">
         < p V-IF = "true" > display when V-IF is true</p>
         < p V-IF = "false" > displayed when V-IF is false</p>
     </div>
     <script>
        var vm = new Vue({
            el: "#app",
            data: {
                true: true,
                false: false,
            }
        })
     </script>
  3. v-ifIs a “real” conditional rendering, because it ensures that theEvent listeners in conditional blocksandSubcomponentsProperly destroyed and rebuilt.
  4. v-ifIs lazy if the initial rendering condition isfalseThen you don’t have to do anything until the first condition becomesreallyTo start rendering the condition block.
  5. v-ifIt is usually used in the following two cases:
    • Among multiple elements, through the condition judgment, theExhibitionperhapshideOne or more elements.
    • Switch between two views.
    • For example, the following code implements: 1) the display of elements when type has different values; ② Click the button to switch the view
      <div id="app">
      <div style=" color:red Simple and practical use of "> V-IF < / div >
      <template>
          <div v-if="type == 'A'">A</div>
          <div v-else-if="type=='B'">B</div>
          <div v-else>C</div>
      </template>
      <div>
          <p>V-IF's spring frame switch</p>
      </div>
      <template v-if="loginType === 'username'">
          < label > User Name: < / label >
          <input placeholder="Enter your username" key="username-input">
      </template>
      <template v-else>
          < label > password: < / label >
          <input placeholder="Enter your email address" key="email-input">
      </template>
      < button @ Click = "changelogintype" > switch state < / button >
      </div>
      <script>
      var app = new Vue({
          el: '#app',
          data: {
              type: 'C',
              loginType: 'username'
          },
          methods: {
              changeloginType() {
                  let self = this;
                  if (self.loginType == 'username') {
                      self.loginType = ''
                  } else {
                      self.loginType = 'username'
                  }
              }
          }
      })
      </script>
  6. Expand understanding – official document:Conditional rendering vue.js

v-else

  1. Introduction: personal feelingv-elseIt’s not like a single function instruction, but it’s partial to auxiliary function, andv-else Must be with v-if Continuous useOtherwise, an error will be reported.
  2. For example:
     <div id="app">
        <p v-if="msg1">The msg1 is true</p>
        <p v-else>The msg1 is false</p>
        <input type="button" @click="button" value="Button"/>
     </div>
     <script type="text/javascript">
        var app = new Vue({
            el: '#app',
            data: {
                msg1: true,
            },
            methods: {
                button: function(){
                    this.msg1 = !this.msg1;
                }
            }
        })
     </script>
    • The above process is calledv-ifAndv-elseIfRemove v-ifPart, the error is: error compiling template
      Vue instruction Encyclopedia (super detailed)

v-else-if

  1. Introduction: andv-elseSame,v-else-ifAnd we have to talk to each otherv-ifIn fact, the reason is very simple, analogyC languageOfifelseelse ifIt’s herev-else-ifAlso used inv-ifandv-elseIn the middle, realize multiple judgments
  2. For example:
    <div id="app">
        < p V-IF = "10 > 20" > V-IF wins</p>
        < p v-else-if = "10 > 5" > v-else-if wins</p>
        < p v-else > well, v-else won</p>
     </div>
     <script type="text/javascript">
        var app = new Vue({
            el: '#app',
        })
     </script>
    • withoutv-ifThen it will be the same as abovev-elseSame error: error in compiling template
      Vue instruction Encyclopedia (super detailed)

v-show

  1. Introduction:v-showIt’s also used toControls whether the element is displayedIts function is similar tov-ifInstructions are similar.
  2. For example:
    <div id="app">
    < p v-show = "MSG" > display success</p>
    <input type="button" @click="show" value="Do you want to hide it?" />
    </div>
    <script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            msg: true,
        },
        methods: {
            show: function(){
                this.msg = !this.msg;
            }
        }
    })
    </script>
  3. So,v-showAndv-ifwhat are you having?contactWhat about it?
    • v-showAndv-ifIt’s all throughOperating DOM dynamicallyTo show and hide
  4. v-showAndv-ifOfdifferenceWhat is it?
    • Different means: v-ifIs to dynamically add or delete DOM elements to the DOM treev-ifThe value of isfalseIt will be deleted in the DOM, which is equivalent tovisibility:hidden;, if yestrueClone the element to the corresponding DOM tree, and support adding<template>On the label; andv-showIs to set DOM elements dynamicallydisplayAttribute without deleting the DOM elementdisplay:none;, adding to is not supported<template>On the label.
    • Different compilation processes: v-ifWhen switching, there will be a local compile / unload process. When switching, the internal event listeners and subcomponents will be destroyed and rebuilt properlyv-ifIt may be data binding or sub components; andv-showIt’s just a simple way to switch CSS properties.
    • Different compilation conditions: v-ifIf the initial condition is false, nothing needs to be done. Only when the condition becomes true for the first time can local compilation be started. The compilation will be cached, and then local unloading will be performed when the condition is switched again; andv-showWhether the value is true or not, it is compiled, then the compilation is cached, and the DOM elements are preserved.
    • Different performance consumption: v-ifIt has higher switching consumption,v-showHas a higher initial rendering consumption
      Therefore, the problem of use is raised
      • When the switching of a certain piece of content in a component is very small, the switching consumption is also very smallv-ifIt’s more appropriate to render
      • If you switch conditions frequently, use thev-showMore appropriate, to achieve a rendering, multiple switching
      • Why do you say that? Frequent operation of DOM will affect performance. Frequent switching means frequent creation and deletion of DOM, which is more appropriate to reduce consumptionv-show; If it is shown or hidden, thenv-ifMore reasonable, because with the help ofv-ifIf its value is false at the beginning, you don’t even need to create a DOM. If its value is true, the effect is the same as that of creating a DOMv-showIt’s exactly the same.
    • Supplement:display:noneAndvisibility:hiddenThe differences between them are as follows:
      • display:noneIt disappears completely, does not occupy a place in the document stream, and the browser will not parse the element;
      • visibility:hiddenIt can be understood as the effect of 0 transparency. It just disappears visually and occupies space in the document stream. The browser will also parse the element.
      • usevisibility:hiddenIt’s better than thatdisplay:noneBetter performance withdisplayWhen switching, the page will generatebackflow(when some elements in the page need to change the size, layout, display and hide, the page needs toRebuildThat is, reflux. When all pages are loaded for the first time, they need to generate a reflowvisibilityThere is no backflow during switching.
    • Add: if an element is set in CSSdisplay:none, you cannot set thev-ifperhapsv-showTo make the element display, because switching will only change the “display” attribute of element. Style to “None” or “block”, and will not override or modify the existing CSS attribute

v-for

  1. v-forLoop normal array:
    <div id="app">
     <p v-for="value in list">{{value}}</p>
     < p V-for = (value, I) in list > index: {I} = > value: {value}}</p>
    <!--  Note: the order of value and index is: (value, I) - -- >
    </div>
    <script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        data: {
            list: [1,2,3,4,5]
        }
    })
    </script>
  2. v-forLoop object array:
    <div id="app">
    <p v-for="(value,i) in list">
        Index: {I} -- ID: {value. ID} -- Name: {value. Name}
    </p>
    </div>
    <script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        data: {
            list: [
                { id: 1, name: 'first' },
                { id: 2, name: 'second' },
                { id: 3, name: 'third' },
            ]
        }
    })
    </script>
  3. v-forLoop object:
    <div id="app">
    <p v-for="(value,key,i) in student">
        Index: {I} -- key: {key} -- Value: {value}
    </p>
    </div>
    <script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            student: {
                id: 0,
                name: 'Tom',
                Gender: 'male'
            }
        }
    })
    </script>
  4. v-forIteration number:
    <div id="app">
    This is the {{count}} th cycle</p>
    </div>
    <script type="text/javascript">
    var app = new Vue({
        el: '#app',
    })
    </script>
  5. v-forInkeyUse of attributes:
    <div id="app">
    <div>
        <label>Id:
            <input type="text" v-model="id" />
        </label>
        <label>Name:
            <input type="text" v-model="name" />
        </label>
        < input type = button "@ Click = add" value = add / >
    </div>
    <p v-for="item in list" :key='item.id'>
        <input type="checkbox" />{{item.id}} --- {{item.name}}
    </p>
    </div>
    <script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            id: '',
            name: '',
            list: [
                {ID: 1, name: 'Liz'},
                {ID: 2, name: 'Ying Zheng'},
                {ID: 3, name: 'Zhao Gao'},
            ]
        },
        methods: {
            add(){
                this.list.unshift({ id: this.id, name: this.name });
            }
        }
    })
    </script>

v-on

  1. Synopsis: it’s comingBinding event listenerYes, so we can interact.
  2. For example:
    <div id="app">
    < input type = "button" v-on: Click = "click" value = "click this pop-up statement" / >
    </div>
    <script type="text/javascript">
    var app = new Vue({
        el: '#app',
        methods: {
            click(){
                alert('Hello Vue!');
            }
        }
    })
    </script>
    • v-onIt can be abbreviated as@

v-bind

  1. Introduction:v-bindInstructions are mainly used forBinding properties, you can dynamically bind one or more attributes, such as class attribute, style attribute, value attribute, and av-bindBinding. Its syntax is:V-bind: attribute name = variable name, regulationsv-bindIt can be abbreviated as:For example, grammar can be abbreviated as: property name = variable name
  2. Bind HTML class:
    • Object syntax: we can pass it tov-bind:classAn object to dynamically switch class attributes, such as:
      <div v-bind:class="{ active: isActive }"></div>
      <script>
      var vm = new Vue({
          el: '#app',
          data: {
              Isactive: true // active can be displayed at this time
          }
      })
      </script>
    • Whether active is displayed depends on whether isactive is true.
    • In addition, multiple attributes can be passed in to dynamically switch classes, such as the following template:
      <div class="static" v-bind:class="{ A:isA, 'B': isB }"></div>
       <script>
          var vm = new Vue({
              el: '#app',
              data: {
                  isA: true,
                  isB: false,
              }
          })
       //The results are rendered as follows: < div class = "static isa" > < / div >
       </script>
    • Of course, the bound object does not need to be defined inline in the template, but is replaced by an object name:
       <div v-bind:class="classObject"></div>
       <script>
          var vm = new Vue({
              el: '#app',
              data: {
                  classObject{
                      isA: true,
                      isB: false,
                  }
              }
          })
       </script>
    • We can also bind a calculation property of the returned object, which is a powerful and commonly used pattern
       <div v-bind:class="classObject"></div>
       <script>
          var vm = new Vue({
              el: '#app',
              data: {
                  isA: true,
                  isB: false,
              },
              computed: {
                  classObject: function () {
                      return {
                          active: this.isA && !this.isB,
                          statiq: this.isB && this.isB.type === 'fatal'
                      }
                  }
              }
          })
       </script>
    • Array syntax: we can pass an array tov-bind:classTo apply a class list:
      <div id="app">
          <div v-bind:class="[activeClass, errorClass]"></div>
       </div>
       <script>
          var vm = new Vue({
              el: '#app',
              data: {
                  activeClass: 'active',
                  errorClass: 'text-danger'
              }
          })
       //Render as < div class = "active text danger" > < / div >
       </script>
  3. Note: Aboutv-bindPlease refer to:Explain v-bind instruction in detailas well asUse of v-bind syntax in vue.js

v-model

  1. Introduction: this instruction is used forCreating bidirectional data binding on a formv-modelThe initial values of the value, checked and selected attributes of all form elements are ignored becausev-modelSelect the Vue instance data as the specific value.
  2. For example:
    <div id="app">
        <input v-model="somebody">
        <p>hello {{somebody}}</p>
    </div>
    <script>
    var app = new Vue({
        el: '#app',
        data: {
            Some body: 'Xiao Ming'
        }
    })
    </script>

v-pre

  1. Introduction:v-premeetingOutput as is, output whatever the content of the tag is. It is mainly used to skip the compilation process of this element and its sub elements, and can be used to display the original mustache tag.
  2. For example:
    <div id="app">
        <p v-pre>{{msg}}</p>
        <p>{{msg}}</p>
    </div>
    <script>
    var app = new Vue({
        el: '#app',
        data: {
            MSG: "v-pre doesn't care about me..."
        }
    })
    </script>

v-cloak

  1. Synopsis: remember the abovePage flickerWell, we can use it, toov-cloakTo solve this problem.
    This instruction is used to remain on the element until the end of the associated instance is compiled.
  2. For example:
    <div id="app" v-cloak> {{context}} </div>
    <script>
    var app = new Vue({
        el: '#app',
        data: {
            context:'Hello Vue!'
        }
    });
    //Using 'v-cloak' will not flash
    </script>

v-once

  1. v-onceAssociated instanceIt will only render once, executeOne time interpolationWhen the data changes, the content of the interpolation will not be updated, and the elements or components defined by v-once will only be rendered once. After the first rendering, they will not be re rendered with the change of the data. If re rendering is involved later, thenIt is associated with the instance and all its childrenWill be consideredStatic contentThis can be used to optimize update performance.
  2. For example:
    <div id="app">
        <p v-once>{{msg}}</p>
        <p>{{msg}}</p>
        <p> <input type="text" v-model="msg" name=""> </p>
    </div>
    <script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            msg: "hello"
        }
    });
    </script>

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]