1. Overview of template syntax

1.1. How to understand front-end rendering?

Fill the data into the HTML tag

1.2. Front-end rendering

  • Native JS concatenated string
  • Use a front-end template engine
  • Use vUE specific template syntax
  • Document fragments document. CreateDocumentFragment
  • Concatenate strings using es6 backquotes

1.2.1. Native JS concatenated strings

Basically, the data is concatenated into HTML tags as strings, and the front-end code style is basically as follows.

Disadvantages: The code styles of different developers vary greatly, and with the complexity of the business, later maintenance becomes increasingly difficult.

var d = data.weather;
var info = document.getElementById('info');
info.innerHTML = ' ';
for(var i=0; i<d.length; i++){var date = d[i].date;
    var day = d[i].info.day;
    var night = d[i].info.night;
    var tag = ' ';
    tag += ' date: '+date+'</sapn><ul>';
    tag += 
  • Daytime weather: '
  • +day[1] +'</li>' tag += '
  • Daytime temperature: '
  • +day[2] +'</li>' tag += Daytime wind direction:+day[3] +'</li>' tag +=
  • Daytime wind speed:
  • +day[4] +'</li>' tag += '</ul>'; var div = document.createElement('div'); div.innerHTML = tag; info.appendChild(div); } Copy the code

    1.2.2. Use a front-end template engine

    The following code is based on the template engine art-template. Compared to concatenated strings, the code is much more formal and has its own set of template syntax rules.

    Advantages: Everyone follows the same rules to write code, code readability significantly improved, convenient later maintenance. Disadvantages: No dedicated event mechanism is provided.

    1.2.3. Overview of template syntax

    • Difference expression
    • instruction
    • event
    • Attributes bind
    • Style binding
    • Branching cycle structure

    2. Instruction

    Liverpoolfc.tv: cn.vuejs.org/v2/api/

    2.1. What is an instruction?

    • The essence of directives is custom properties
    • The format of the command: begin with a V – (e.g., v-cloak)

    2.2. Usage of the V-cloak command

    2.2.1. Why is there flicker problem?

    When you load your code, you load the HTML first and you load the interpolation syntax on the page as HTML content and then you replace the interpolation syntax after you load the JS so you see flicker problems

    2.2.2. How to solve the flicker problem of interpolation syntax?

    v-cloak

    2.2.3. Principle of solving this problem

    Hide and replace the value before displaying the final value

    <style type="text/css">
      # # # # # # # # # # # # # #
      [v-cloak]{
        /* Element hidden */
        display: none;
      }
      </style>
    <body>
      <div id="app">
        <! The "V-cloak" attribute will be removed as soon as the data is rendered. The "V-cloak" attribute will be removed as soon as the data is rendered. The "V-cloak" attribute will be removed as soon as the data is rendered.
        <div  v-cloak  >{{msg}}</div>
      </div>
      <script type="text/javascript" src="js/vue.js"></script>
      <script type="text/javascript">
        var vm = new Vue({
          // el specifies that the element ID is the element of app
          el: '#app'.// Data stores data
          data: {
            msg: 'Hello Vue'}});</script>
    </body>
    </html>
    Copy the code

    2.3. Data binding instructions

    2.3.1. V – text

    • V-text fills plain text
    • The V-text instruction is used to fill labels with data, similar to interpolation, but without the flash problem
    • If there is an HTML tag in the data, the HTML tag is output
    • Note: this is one-way binding, the value of the data object changes, the interpolation will change; However, changes in interpolation do not affect the value of the data object
    <div id="app"> <! - note: don't write interpolation grammar in the instruction Write the corresponding variable name directly In the v - text assignment of time don't write in interpolation syntax General attributes do not add {{}} to write directly in the corresponding data name -- -- ><p v-text="msg"></p>
        <p>
            <! Vue uses interpolation syntax only for tag content.
            {{msg}}
        </p>
    </div>
    
    <script>
        new Vue({
            el: '#app'.data: {
                msg: 'Hello Vue.js'}});</script>
    Copy the code

    2.3.2. V – HTML

    • The usage is similar to v-text but it can be used to fill HTML fragments into tags
    • There may be security issues and it is generally only used for trusted contentv-html.neverFor user-submitted content
    • The difference between V-text and V-text is that V-text outputs plain text. The browser does not parse it in HTML, but V-HTML outputs it as AN HTML tag.
    <div id="app"><p v-html="html"></p><! Output: HTML tags are parsed at render time --><p>{{message}}</p><! -- Output: <span> bound by double parentheses </span> --><p v-text="text"></p><! </span> --> </div><script>
      let app = newVue({el: "#app".data: {message: " bind by double parentheses ".html: " HTML tags are parsed during rendering ".text: " HTML tags are outputted at render time ",}});</script>
    Copy the code

    2.3.3. V – pre

    • Displaying the raw information skips compilation
    • Skip the compilation of this element and its children.
    • Some static content does not need to be compiled with this command to speed up rendering
        <span v-pre>{{ thiswill not be compiled }}</span> <! -- displays {{this will not be compiled }}  -->
    	<span v-pre>{{msg}}</span><! {{MSG}} --><script>
        new Vue({
            el: '#app'.data: {
                msg: 'Hello Vue.js'}});</script>
    Copy the code

    2.4. Data responsiveness

    2.4.1. How to understand reactive

    • ① Responsiveness in HTML5 (changes in screen size lead to changes in style)
    • ② Responsiveness of data (changes in data lead to changes in page content)

    2.4.2. What is data binding

    Data binding: Populates the label with data

    2.4.3. V – once

    • Only compile once
    • There is no longer responsiveness after displaying content
    • Perform a one-time interpolation [when data changes, the content of the interpolation does not continue to update]
    <! "Hello vue.js" -- "Hello vue.js" -- "Hello vue.js" --<span v-once>{{ msg}}</span>    
    <script>
        new Vue({
            el: '#app'.data: {
                msg: 'Hello Vue.js'}});</script>
    Copy the code

    3. Bidirectional data binding instructions

    3.1. What is two-way data binding?

    • When the data changes, the view changes
    • As the view changes, so does the data

    3.2. Bidirectional data binding analysis

    3.2.1. Usage of V-model instruction

    • Model is an instruction, restricted to<input>,<select>,<textarea>And components
     <div id="app">
          <div>{{msg}}</div>
          <div>When the content in the input box changes, the MSG on the page will be updated automatically<input type="text" v-model='msg'>
          </div>
      </div>
    Copy the code

    3.3. MVVM design idea

    MVC is a back-end layered development concept; MVVM is the concept of the front View layer, which mainly focuses on the separation of the View layer. That is to say, MVVM divides the front View layer into three parts: Model, View and VM ViewModel

    • (1) M (model)
      • Data layer The data layer in Vue is placed inside data
    • ② V(view)
      • The View in Vue is our HTML page
    • ③ THE VM(View-Model) controller connects data with the View layer
      • Vm, an instance of Vue, is VM

    4. Event binding

    4.1. How does Vue handle events?

    4.1.1. Usage of V-ON instruction

    Used to bind events

    < input type = "button' v-on:click='num++'/ >Copy the code

    4.1.1.1. Shorthand for V-ON

    < input type = "button' @click='num++'/ >Copy the code

    4.2. Call method of event function

    4.2.1. Directly bind function names

    <button v-on:click='say'>Hello</button>
    Copy the code

    4.2.2. Calling functions

    <button v-on:click='say()'>Say hi</button>
    Copy the code

    4.3. Event function parameter passing

    4.3.1. Common Parameters and event objects

    4.3.1.1. how to use the event object in vue

    • By default event parameters
    • Used by $event
    <button v-on:click='say("hi",$event)'>Say hi</button>
    Copy the code
    <body>
        <div id="app">
            <div>{{num}}</div>
            <div>
                <! If the event is directly bound to the function name, then the event object is passed as the first argument to the event function by default.
                <button v-on:click='handle1'>Click on the 1</button>
                <! If the event is called, the event object must be passed as the last argument, and the name of the event object must be $event -->
                <button v-on:click='handle2(123, 456, $event)'>Click on the 2</button>
            </div>
        </div>
        <script type="text/javascript" src="js/vue.js"></script>
        <script type="text/javascript">
            var vm = new Vue({
                el: '#app'.data: {
                    num: 0
                },
                methods: {
                    handle1: function(event) {
                        console.log(event.target.innerHTML)
                    },
                    handle2: function(p, p1, event) {
                        console.log(p, p1)
                        console.log(event.target.innerHTML)
                        this.num++; }}});</script>
    Copy the code

    4.4. Event modifiers

    • Called in an event handlerevent.preventDefault()event.stopPropagation()Is a very common requirement.
    • Vue does not recommend that we manipulate DOM. To solve this problem, Vuev-onprovidesEvent modifier
    • Modifiers are represented by an instruction suffix beginning with a dot
    <! -- Prevent the click event from propagating --><a v-on:click.stop="doThis"></a><! Submit events no longer reload the page --><form v-on:submit.prevent="onSubmit"></form><! -- modifiers can be concatenated to prevent both bubbling and default events --><a v-on:click.stop.prevent="doThat"></a><! Trigger handler only if event.target is the current element itself --> <! -- that is, events are not triggered from internal elements --><div v-on:click.self="doThat">.</div>When using modifiers, order is important; The corresponding code is generated in the same order. Therefore, using V-on :click.prevent. Self blocks all clicks, whereas V-on :click.self. Prevent only blocks clicks on the element itself.Copy the code

    4.4.1..stopTo prevent a bubble

    <a v-on:click.stop="handle"> jump < / a >Copy the code

    4.4.2. .preventBlocking default behavior

    <a v-on:click.prevent="handle"> jump < / a >Copy the code

    4.5. Key modifier

    Keyboard events are sometimes used in projects, and when listening for keyboard events, we often need to check for detailed keystrokes. Vue allows you to add key modifiers for V-Ons when listening for keyboard events

    <! Only in -`keyCode`13Called when the`vm.submit()`--> <input v-on:keyup.13="submit"> <! 'vm.submit()' --> <input V-on :keyup.enter="submit"> 'vm.alertMe()' --> <input type="text" v-on:keyup.enter.space="alertMe" > Esc => Cancel. Space => Spacebar. Up => up. down => down. left => left. right => right <script> var vm = new Vue({ el:"#app", methods: { submit:function(){}, alertMe:function(){}, } }) </script>Copy the code

    4.5.1. .enterThe enter key

    <input v-on:keyup.enter='submit'>
    Copy the code

    4.5.2. .escEscape key

    <input v-on:keyup.delete='handle'>
    Copy the code

    4.6. Customize key decorators

    You can customize key modifier aliases in Vue via config.keyCodes

    <div id="app"Keycode is pre-defined116The alias for F5 is F5, so pressing F5 in the text input box triggers the prompt method <input Type ="text" v-on:keydown.f5="prompt()">
    </div>
    
    <script>
    	
        Vue.config.keyCodes.f5 = 116;
    
        let app = new Vue({
            el: '#app'.methods: {
                prompt: function() {
                    alert('I'm F5! '); }}});</script>
    Copy the code

    4.6.1. Global config.keycodes objects

    Vue.config.keyCodes.f1 = 112
    Copy the code
    • Note the keycode value for the 112 keyboard
    • F1 can customize any name

    5. Property binding

    5.1. How does Vue handle attributes dynamically?

    5.1.1. Usage of the V-bind instruction

    Directives are used to update HTML attributes in response

    <a v-bind:href='url'> jump < / a >Copy the code

    5.1.2. Abbreviations

    <a :href='url'> jump < / a >Copy the code
    1. Analysis of the low-level realization principle of V-Model
    <input v-bind:value="msg" v-on:input="msg=$event.target.value">
    Copy the code

    6. Style binding

    6.1. Class style handling

    Note: The V-bind :class directive can coexist with the normal class feature

    6.1.1. Object syntax

    • By v-bind:class = {key: value}
    • The key represents a class name and if the value is true, the class name is displayed
    • If the value is false, the class name is not displayed
    1If you bind an object, the key is the class name and the value is the data in the corresponding data <! -- HTML renders to <ulclass="box textColor textSize"></ul> Note: textColor, textSize corresponds to the CSS class name isColor rendered on the page, isSize corresponds to the data in vue data iftrueThe corresponding class name is rendered to the page when isColor and isSize change,classThe list will be updated accordingly, for example, willisSizetofalse.classThe list will become <ul class="box textColor"></ul>
    -->
    
    <ul class="box" v-bind:class="{textColor:isColor, textSize:isSize}">
        <li>Learning Vue</li>
        <li>Learning Node</li>
        <li>Learning the React</li>
    </ul>
      <div v-bind:style="{color:activeColor,fontSize:activeSize}">Object syntax</div>
    
    <sript>Var vm= new Vue({el:'. Box ', data:{isColor:true, isSize:true, activeColor:"red", activeSize:"25px",}})</sript>
    <style>
    
        .box{
            border:1px dashed #f0f;
        }
        .textColor{
            color:#f00;
            background-color:#eef;
        }
        .textSize{
            font-size:30px;
            font-weight:bold;
        }
    </style>
    Copy the code
    <div v-bind:class="{ active: isActive }"></div>
    Copy the code

    6.1.2. Array syntax

    • By v-bind:class =[value 1, value 2]
    • Values 1 and 2 correspond to data in data
    2V-bind supports the ability to bind an array where classA and classB correspond to data in data and classA in data and classB in data and classB <ul in dataclass="box" :class="[classA, classB]">
        <li>Learning Vue</li>
        <li>Learning Node</li>
        <li>Learning the React</li>
    </ul>
    <script>
    var vm= new Vue({
        el:'.box'.data: {classA: 'textColor',classB: 'textSize'}})</script>
    <style>
        .box{
            border:1px dashed #f0f;
        }
        .textColor{
            color:#f00;
            background-color:#eef;
        }
        .textSize{
            font-size:30px;
            font-weight:bold;
        }
    </style>
    Copy the code
    <div v-bind:class="[activeClass, errorClass]"></div>
    Copy the code

    6.1.3. Differences between bound objects and bound arrays

    • When you bind an object, the property of the object is the name of the class to be rendered and the property value of the object corresponds to the data in data
    • When you bind an array, it holds the data in data

    6.1.4. Can object binding and array binding be mixed?

    • An array can store any data type
    • Any data type can also be stored in the value of an object

    6.2. Style style processing

     <div v-bind:style="styleObject"> Bind style object </div>'<! --> <div v-bind:style=" color: activeColor, fontSize: activeColor; fontSize,background:'red'}"> inline style </div> <! <div v-bind:style="[styleObj1, styleObj2]"></div> <script> new Vue({el: ')#app', data: { styleObject: { color: 'green', fontSize: '30px', background:'red'}, activeColor: 'green', fontSize: "30px" }, styleObj1: { color: 'red' }, styleObj2: { fontSize: '30px' } Copy the code

    6.2.1. Object syntax

    • V-bind :style = {key: value}
    • The key represents the CSS property value and stores the CSS property value
    <div v-bind:style="{ color: activeColor, fontSize: fontSize }"></div>
    Copy the code

    6.2.2. Array syntax

    • V-bind :style = [value 1, value 2]
    • The values 1 and 2 in the array store an object that stores CSS properties and property values
    <div v-bind:style="[baseStyles, overridingStyles]"></div>
    Copy the code

    7. Branch cycle structure

    7.1. Branch structure

    • v-if
    • v-else
    • v-else-if
    • v-show

    7.1.1. V-if Application Scenario

    • 1- Multiple elements show or hide an element by conditional judgment. Or multiple elements
    • 2- Switch between two views
    <div id="app"> <! If true, load it, otherwise not --><span v-if="flag">If flag is true, it is displayed; false, it is not displayed!</span>
    </div>
    
    <script>
        var vm = new Vue({
            el:"#app".data: {flag:true}})</script>
    
    ----------------------------------------------------------
    
        <div v-if="type === 'A'">
           A
        </div><! -- v-else-ifKeep up with the v -ifOr v -else-ifAnd then v minusifExecution when conditions are not standing --><div v-else-if="type === 'B'">
           B
        </div>
        <div v-else-if="type === 'C'">
           C
        </div><! -- v-elseKeep up with the v -ifOr v -else-ifAfter -- -- ><div v-else>
           Not A/B/C
        </div>
    
    <script>
        new Vue({
          el: '#app'.data: {
            type: 'C'}})</script>
    Copy the code

    7.2. Difference between V-IF and V-show

    • V-show is essentially the tag display set to None, which controls hiding
      • V-show compiles only once and controls CSS, whereas V-if destroys and creates all the time, so v-show performs better.
    • V-if dynamically adds or removes DOM elements from the DOM tree
      • The V-IF switch has a partial compile/unload process in which the internal event listeners and subcomponents are destroyed and rebuilt as appropriate

    An overview of the

    • V-if controls whether elements are rendered to the page
    • V-show controls whether elements are displayed (already rendered to the page)

    7.3. Circular structure

    7.3.1. V-for traversal number group

    <li v-for='item in list'>{{item}}</li>
    <li v-for='(item,index) in list'>{{item}} + '---' +{{index}}</li>
    Copy the code

    7.3.2. Key helps Vue differentiate between different elements to improve performance

    • Key to give each node a unique identity
    • The key’s main purpose is to update the virtual DOM efficiently
    <li :key='item.id' v-for='(item,index) in list'>{{item}} + The '-' {{index}}</li>
    Copy the code

    7.3.3. v-for traverses objects

    <div v-for='(value, key, index) in object'></div>
    Copy the code
    • Value represents each item in the object
    • Key indicates the corresponding Key name
    • Index Indicates the corresponding Index

    7.3.4. V-if and V-for are used together

    • Is not recommendedAt the same time usev-ifv-for
    • whenv-ifv-forWhen used together,v-forIs better thanv-ifHigher priority.
    <div v-if='value==12' v-for='(value, key, index) in object'></div>
    Copy the code