Essential knowledge points for getting started with Vue

    Vue summary 1.0 mainly includes Vue basic syntax, computed properties, concepts, and instructions

    Vue MVVM

    MVVM helps to separate the development of GUI from the development of business logic or backend logic (data model)
    View layer (view layer):
    In front-end development, it is usually the DOM layer. The main function is to display various information to the user, that is, the structure, layout and appearance (UI) seen.
    Model layer (data layer):
    The data representing the real content, the data may be fixed, but more of it is the data requested from the server.
    VueModel layer (view model layer):
    The view model layer is the bridge between View and Model. On the one hand, it implements Data Binding, that is, Data Binding, which reflects the changes of Model to View in real time; on the other hand, it implements DOM Listener, that is, DOM Monitoring, when DOM happens Some events (click, scroll, touch, etc.) can be monitored and the corresponding Data can be changed if necessary.


    Vue template

    <body>
    <div id="app">
       {{message}}
    </div>
    <script src="../js/vue.js"></script>
    <script>
    const app = new Vue({
         el: '#app',
         data: {
           message: 'Hello'
         }
         })
    </script>
    </body>
    


    1. Vue list display

    <div id="app">
    <ul>
         <li v-for="item in movies">{{item}}</li>
    </ul>
    <script>
    const app = new Vue({
         el: '#app',
         data: {
             message: 'Hello',
             movies: ['Interstellar Crossing', 'A Westward Journey', 'Youth Pi', 'Inception']
         }
    })
    </script>
    


    2. Counter

    Just as the page directly uses the value in {{data, eg: count}}, the tag in the body needs to use the value of data in vue directly

    <h3>The current value is: {{count}}</h3>
    <button @click="count++">+</button>
    

    But in vue, methods and other data that need to use data have to add this, because there is no data in data in methods.

    methods:{
            add:function(){
                this.count++
            }
        }
    

    PS: The methods in vue cannot use the arrow function, because this does not point to the vue instance, use the arrow function to print this, and find that it is undefined

    methods: {
    test: () => {
        console.log(this); // undefined
    }
    }
    


    3. Vue directives

    1. v-html

    This instruction is often followed by a string type and the html in the string is parsed and rendered

    <h3 v-html="message"></h3>
       <script>
       const app = new Vue({
         el: '#app',
         data: {
           message: '<span>Hello</span>'
         }
       })
    </script>
    //span tag can be parsed by v-html
    

    2. v-once

    Elements and components are only rendered once and will not change as the data changes

    3. v-cloak

    This directive remains on the element until the associated instance finishes compiling. When used with CSS rules such as [v-cloak] { display: none }, it is possible to hide uncompiled Mustache tags until the instance is ready.

    [v-cloak] {
       display: none;
    }
    <div id="app">
       <h2>{{message}}</h2> <!-- v-cloak not used -->
       <h2 v-cloak>{{message}}</h2>
    </div>
    <script>
       setTimeout(function () {
         const app = new Vue({
           el: '#app',
           data: {
             message: 'Hello'
           }
         })
       }, 1000)
    </script>
    

    4. v-bind

    (syntactic sugar :) <img v-bind:src="imgURL" alt=""> ===<img :src="imgURL" alt="">

    • v-bind dynamic binding class (dynamic binding is object)

      <style>
            .active {
              color: red;
            }
            .small {
              font-size: 15px;
            }
          </style>
        </head>
        <body>
          <div id="app">
            <!-- Method 1: By judging the binding class and not conflicting with the original class -->
           <!--<h2 v-bind:class="{class name 1: true, class name 2: false}">{{message}}</h2>-->
      
            <h2 class="small" :class="{active: isActive}">Test Text 1</h2>
            <!-- Attributes can be added or not quoted -->
            <h2 :class="{'active':isActive}">Test Text 2</h2>
      
            <!-- Method 2: Dynamic binding is placed in methods -->
            <h2 :class="getClasses()">Test Text 3</h2>
      
            <!-- Method 3: Dynamically bind the computed property of the returned object -->
            <h2 :class="getClass">Test Text 4</h2>
      
            <p></p>
            <button @click="btnClick">button</button>
          </div>
      
          <script>
            const app = new Vue({
              el: '#app',
              data: {
                isActive: false,
                active: 'active',
              },
              methods: {
                btnClick: function () {
                  this.isActive = !this.isActive;
                },
      
                getClasses: function () {
                  return { active: this.isActive };
                   //Return active in object form: this.isActive, that is, :class="getClasses() becomes :class="{'active':isActive}"
                },
              },
              computed: {
                getClass: function () {
                  return { active: this.isActive, };
                },
              },
            });
          </script>
        </body>
      

    Before and after clicking the button:

    • v-bind dynamic binding class (dynamic binding is array)

      <style>
            .active {
              color: red;
            }
            .small {
              font-size: 15px;
            }
          </style>
          <div id="app">
      
            <!-- Bind several class names directly through an array -->
            <h2 :class="[active, small]">Test Text 1</h2>
      
            <!-- array and ternary operator -->
            <h2 :class="[isActive?'active':'']">Test Text 3</h2>
      
            <!-- By method binding -->
            <h2 class="small" :class="getClasses()">Test Text 3</h2>
            <p></p>
            <button v-on:click="btnClick">button</button>
          </div>
      
          <script src="../js/vue.js"></script>
          <script>
            const app = new Vue({
              el: '#app',
              data: {
                active: 'active',
                small: 'small',
                isActive: false,
              },
              methods: {
                btnClick: function () {
                  this.isActive = !this.isActive;
                },
      
                getClasses: function () {
                  return [this. active];
                  //Return [this.active]([active]) in the form of an array, that is, :class="getClasses() is equivalently changed to: class=[active]
      
                },
              },
            });
          </script>
      

    5. v-on (abbreviation: @)

    .once : Trigger the callback only once.
    .stop : Call event.stopPropagation().
    .prevent : Call event.preventDefault().

    <!-- stop bubbling -->
    <button @click.stop="doThis"></button>
    
    <!-- prevent default behavior -->
    <button @click.prevent="doThis"></button>
    
    <!-- prevent default behavior, no expression -->
    <form @submit.prevent></form>
    

    @click="btnClick()The parentheses of the v-on method can be written or not, but if the parentheses are omitted when writing the method but the method itself requires a parameter, Vue will default to the event event object produced by the browser as parameter passed into the method

    When the method is defined, if you need the event object and other parameters at the same time, you need to manually obtain the event object of the browser parameter: $event

    <div id="demo">
    <button @click = "btnClick('abc',$event)">button</button>
    </div>
      const demo = new Vue({
         el:'#demo',
         methods: {
             btnClick: function(a, event) {
                 console. log(a, event);
             }
         }
       })
    


    6. v-if

    When used with v-if, v-for has higher priority than v-if.

    <h2 v-if="score>=90">Excellent</h2>
    <h2 v-else-if="score>=80">Good</h2>
    <h2 v-else-if="score>=60">Pass</h2>
    <h2 v-else>failing</h2>
    


    7. v-for

    It is recommended to add :key=, the main function of the key is to update the virtual DOM efficiently
    Do not use non-primitive values like objects or arrays as v-for keys. Please use a string or numeric value.

    <li v-for="(item,index) in names">{{item}}-{{index}}</li>
    v-for="(value, name, index) in object"
    


    8. v-model: Realize two-way binding between form elements and data

    principle:
    Contains two operations:
    1. v-bind binds a value attribute;
    2. v-on command binds the input event to the current element to update the value <input type="text" :value="message" @input="message = $event.target.value">

    v-model can also bind radio buttons and check boxes

    <h2>Your hobbies are: {{hobbies}}</h2>
       <label v-for="item in originHobbies" :for="item">
         <input type="checkbox" :value="item" :id="item" v-model="hobbies">{{item}}
       </label>
    </div>
    
    <script>
       const app = new Vue({
         el: '#app',
         data: {
           hobbies: [], // multiple selection box,
           originHobbies: ['basketball', 'football', 'table tennis', 'badminton', 'billiards', 'golf']
         }
       })
    </script>
    

    Modifiers for v-model:
    lazy modifier:
    By default, v-model will synchronize the data of the input box in the input event by default, but the lazy modifier can be converted to synchronize after a custom event. Such as: update when losing focus or pressing the Enter key <input v-model. lazy="msg">
    number modifier:
    By default, the input box treats the input data as a string type, and the number modifier allows the content of the input box to be automatically converted into a numeric type
    <input type="number" v-model. number="age">
    <h2>{{age}} {{typeof age}}</h2>
    trim modifier:
    Automatically filter the leading and trailing blank characters entered by the user <input type="text" v-model. trim = "mes">


    4. Vue computed properties

    Note: There is no need to add () to the calculated attribute, there must be a return value

    <div id="example">
       <p>{{ message }}</p>
       <p>{{reversedMessage }}</p>
    </div>
    var vm = new Vue({
       el: '#example',
       data: {
         message: 'Hello'
       },
       computed: {
         // getter for the computed property
         reversedMessage: function () {
           // `this` points to the vm instance
           return this. message. split(''). reverse(). join('')
         }
       }
    })
    

    Computed property cache vs method
    Computed properties are cached based on their reactive dependencies. They are only re-evaluated when the relevant reactive dependencies change

    computed: {
      now: function () {
        return Date.now()
      }
    }
    

    Computed properties are not updated, but in contrast, calling the method will always execute the function againwhenever a re-render is triggered**

    Reason for computing property caching:
    (Official website explanation) Suppose we have a computational property A with relatively high performance overhead, which needs to traverse a huge array and do a lot of calculations. Then we may have other computed properties that depend on A. Without caching, we would inevitably execute A's getter multiple times. If you don't want caching, use method instead.


    References

    Vue.js documentation

    Popular posts from this blog

    大学资料分享——广工计院各个科目实验报告、课设及期末复习资料!!

    Win10 远程计算机或设备将不接受连接

    JAVA Traffic Signal Light Course Design (Source Code + Report + Video Demonstration)