Vue.js basic syntax introductory statement Vue learning notes v-model bidirectional data binding

Vue.js basic grammar, introductory statements, Vue learning notes

Learning website: https://www.bilibili.com/video/BV15741177Eh

vue experience
  1. Responsive: once the data changes, the view will respond to the change

  2. el: specifies which element this Vue object is attached to

  3. Data: this attribute usually stores some data

    <div id="app">{{massage}}</div>  <!-- display helleWorld -->
    <script src="./vue.js"></script> // Import Vue JS file
    <script>
     var  vm = new Vue({  // Create a Vue instance object
         el:"#App ", / / mount to the element with id app (div)
         data:{           // Data is the property of a Vue object that stores data
             massage:"helleWorld"
         }
     })
    </script>
    
MVVM in Vue
  1. M: Model = = > Data
  2. 5: V iew = > viewm
  3. VM: ViewModel = = > DOM listening, data binding
  4. Once the data (model) changes and the VM hears it, it will change the view (V)
life cycle
  1. Life cycle: the process of things from creation to destruction

  2. Declare periodic function, which is automatically created by Vue. It has a life cycle

  3. Common life cycle functions

    • New vue() = = > start creating a Vue instance object

    • Init() = = > start initializing Vue instance objects. At this time, there are only default lifecycle functions and default events

    • Beforecreate() {} = = > when boforeCreate is executed, the data in data and methods has not been initialized

    • Create() {} = = > when create is executed, you can call the data in data and the methods in methods

    • beforeMount() {} = = > when beforeMount is executed, the template has been compiled in memory, but it is not mounted in the page,

      At this time, the page is still old and DOM already exists in memory, so DOM operation cannot be performed at this time

    • Mounted() {} = = > when mount is executed, the template compiled in memory is replaced into the browser page. At this time, DOM operation can be carried out

    • beforeUpdate() {} = = > when beforeUpdate is executed, the actual data in the page is old, but the data in the data is new, and the page has not been synchronized with the latest data

    • Update() {} = = > when updata is executed, re render the latest DOM in memory according to the latest data in data, and then replace the old page with the latest dom

    • Deforedestroy() {} = = > when deforedestroy is executed, Vue instances, from the running phase to the destruction phase, are in the usable state of data, methods, fillers, etc

    • Destroyed () {} = = > when destroyed is executed, the component has been completely destroyed. At this time, the data, methods, instructions and filters are no longer used

  4. demo

    var vm = new Vue({
        el:'#app',
        data: {},
        methods: {},
        beforeCreate(){},
        create(){},
        beforeMount(){},
        mounted(){},
        beforeUpdate() {},
        updated() {},
        beforeDestroy(){},
        destroyed(){}
    }
    
Basic grammar
  • {{}} will not replace the original content

  • v-once: not responsive, data changes, but the view does not change]

  • v-text: the original content of the point will be replaced and output as text

  • v-html: it will replace the original content and output it in HTML syntax

  • v-pre output as is

  • V-cloak: solve the flicker problem, add the style display:none in style, and add v-cloak to div

    Before vue parsing, div has an attribute v-cloak

    After vue parsing, there is no attribute v-cloak in div

  • case

    <style>
        [v-cloak]{
            display: none;
        }
    </style>
    <body>
        <div id="app" v-cloak> <!-- Solve flicker problem:When Vue Appears when the load is not complete{{message}} -->
            <h2>{{message}} Hello</h2><!--helleWorld Hello  -->
            <h2 v-once>{{message}}</h2> <!--message Change, but still show the original content  -->
            <h2 v-text="url">Hello</h2><!-- The original content will be replaced,Output as text-->
            <h2 v-html="url">Hello</h2><!-- Will replace the original content,with html Syntax output of-->
            <h2 v-pre>{{message}}Hello</h2><!-- The original content will not be replaced,Output expression text -->
        </div>    
        <script src="./vue.js"></script>
        <script>
            let vue = new Vue({
                el:"#app",
                data:{
                    message:"helleWorld",
                    url:"<a href='http:www.baidu.com'>use Baidu Search</a>",
                }
            })
        </script>
    
Binding properties
  • v-bind:src="url"

  • v-bind:href="Href"

  • : bind:title = "Text" colon abbreviation

    <img v-bind:src="imgUrl" width="300"> //src is:/ img/1.jpg
    <a :href="aHref">use Baidu Search</a>  //href: http://www.baidu.com
    <h2 :title="titleText">little cat</h2>  //title:animal
    
    data: {
        imgUrl: "./img/1.jpg",
        aHref:"http://www.baidu.com",
        titleText:"animal"
      }
    
  • : class, in the form of key value pairs of objects, or a method can be used to return an object

    <div id="app">
        <!-- binding class Property, in curly braces, in the form of key value pairs -->
        <h2 v-bind:class="{active:isActive,big:isBig}">helle</h2>
        <h2 v-bind:class="getStyle()">helle</h2>
        <!-- Register events, control class The value of the property -->
        <button v-on:click="changeColor">color</button>
        <button v-on:click="changeSize">size</button>
    </div>
    
    data: {
        isActive: true,
        isBig: false	 
     },
    methods: {
        getStyle:function(){
            return {active:this.isActive,big:this.isBig}
        },
        changeColor: function () {
            this.isActive = !this.isActive;
        },
        changeSize: function () {
            this.isBig = !this.isBig
        }
    }
    
  • : class, bind a class attribute in the form of an array, or use a method to return an array

    <div id='app'>  
        <!--Quoted, string class="active line" -->
        <h2 :class="['active','line']">Quotation marks</h2>
        <!--No quotes, variable class="color font-size" -->
        <h2 :class="[active,size]">No quotation marks</h2>
        <h2 :class="getStyle()">Method returns the form of an array</h2>
    </div>
    
    data: {
      active:'color',
      size:'font-size'
     },
    methods: {
      getStyle:function(){
        return [this.active,this.size]
      }
    }
    
Calculation properties
  1. The computed attribute, like data, is an attribute of a Vue

  2. If there is a cache, the data change will be triggered and the result will be returned. If the calculated attribute is used many times, the code will be executed only once. Because there is a cache, the method will execute the code many times at that time.

  3. There are getter method and setter method. Setter method accepts the new value of fullName

  4. The set method is triggered when fullName is reassigned, and the parameter accepted by the method is newvalue; If the firstname or lastName changes, the get method is triggered. The parameters accepted by the get method are vue instances. The parameters of both methods are not required

    computed:{
        fullName:{
            // Trigger set method when fullName is reassigned
            set:function(newValue){
                console.log("set Method triggered,Parameter is:",newValue)
            },
            get:function(newValue){ 
             // If the firstname or lastName changes, the get method is triggered
                console.log("get Method triggered,Parameter is:",newValue==this)
                return this.firstName + this.lastName
            }
        }
     }
    
  5. We usually don't need the set method, so we can write the calculation property like this. The default is the get method:

    computed:{
        fullName:function(){
            return this.firstName + this.lastName
        }
     }
    
event listeners
  1. Using v-on to bind click events, first declare the function in methods before calling

    <div id='app'>
        {{counter}}
        <button v-on:click="add">+</button> <!-- Bind click event -->
        <button v-on:click="sub">-</button> <!-- Bind click event -->
    </div>
    
    <script>
    var vm = new Vue({
        el:'#app',
        data: {
            counter:0
        },
        methods: {
            add(){ //Define an addition function
                this.counter++ 
            },     //Define a subtraction function
            sub:function(){
                this.counter--
            }
        }
    
  2. Abbreviation @ click = v-on:click

    <button @click="add">+</button>
    <button @click="sub">-</button>
    
  3. Bind keyboard event, the keyboard event bound to the button. Point a button and click the keyboard to trigger it

    // Pop up event of any key on the keyboard
    <button @keyup="add">Keyboard bounce event</button>
    // Event when enter key pops up
    <button @keyup.enter="add">Keyboard bounce event</button>
    // Keyboard arbitrary key falling event
    <button @keydown="add">Keyboard bounce event</button>
    //  enter key falling event
    <button @keydown.enter="add">Keyboard bounce event</button>
    
v-on modifier
  1. Common v-on modifiers

    • Stop stop event bubbling
    • prevent block default events
    • Once triggers the callback function only once
    • keyup listens for a keyboard event
    <!-- stop Use of modifiers -->
    <div @click="divClick">DIV
        <button @click.stop="btnClick">Button</button><!--Prevent event bubbling -->       
    </div>
    
    <!-- prevent Use of modifiers to block default events -->
    <form action="http://www.baidu.com">
        <input type="submit" value="Submit jump" @click="submitClick">
        <input type="submit" value="Submit without jump" @click.prevent="submitClick">
    </form>
    
    <!-- keyup Monitor a key and press enter to trigger -->
    <input type="text" @keyup.enter="keyUp"><br>
    
    <!-- once,Just trigger a callback-->
    <button @click.once="onceClick">Button</button>
    
    methods: {
        divClick(){
            console.log("div");
        },
        btnClick(){
            console.log("button")
        },
        submitClick(){
            console.log("submitClick")
        },
        keyUp(){
            console.log("keyUp");
        },
        onceClick(){
            console.log("onceClick")
        }
    }
    
v-on parameter, event object and bracket problem
  1. With parentheses and parameters, the object of event is accepted

    <div id='app'>
        <!-- 1,The method called by the event has no parameters,There is a return value, -->
        <button @click="btn1Click" :title="btn1Click">Button 1</button> <!-- title:function   MouseEvent -->
        <button @click="btn1Click()" :title="btn1Click()">Button 1</button><!-- MouseEvent -->
        <button @click="btn1Click($event)">Button 1</button><!--accept event event-->
    
        <!-- 2,The method called by the event has a parameter, but the parentheses are omitted, vue meeting
             It will be produced by browser by default event The event object is passed in as a parameter -->
        <button @click="btn2Click">Button 2</button><!-- My name is:  MouseEvent -->
        <button @click="btn2Click()">Button 2</button><!-- My name is: undefined -->
        <button @click="btn2Click('Xiao Yi')">Button 2</button><!--My name is:Xiao Yi -->
    
        <!-- 3,The method called by the event requires event Object, and other parameters are required at the same time,You can add one $ -->
        <button @click="btn3Click('cat',$event)">Button 3</button> <!-- animal: cat MouseEvent   -->
    </div>
    
    <script>
    var vm = new Vue({
        el:'#app',
        data: {},
        methods: {
            btn1Click(){
                console.log(event)
                return "title"
            },
            btn2Click(name){
                console.log("My name is:",name,)
            },
            btn3Click(animal,event){
                console.log("animal:",animal,event)
            }
        }
     })
    </script>
    
Small case
  1. Use the v-for circular list to register click events. When clicking a list item, it has a highlighting effect

  2. Method 1:

    <div id='app'>
        <ul ref="ul">
            <li 
            v-for="(item,index) in mens"
            v-on:click="active(index)">{{index+1}}  {{item}}</li>
        </ul>
    </div>
    <script src='./vue.js'></script> 
    <script>
    var vm = new Vue({
        el:'#app',
        data: {
            mens:["Xiao Yi","Xiao Jie","Xiao Miao","puppy","Meow"]
        },
        methods: {
            active:function(index){        
                // console.log(this.$refs['ul'].children)
                lis = this.$refs.ul.children
                for(let i = 0;i < lis.length;i++){
                   if(i == index){
                    lis[i].style.backgroundColor="red"
                   }else{
                    lis[i].style.backgroundColor=""
                   }
                }
            }
        }
     })
    </script>
    
  3. Method 2:

    <style>
        .active{
            background-color: red;
        }
    </style>
    
    <div id='app'>
        <ul ref="ul">
            <li 
            v-for="(item,index) in mens"
            :class="{active: index === currentIndex}" 
            @click="currentIndex = index">{{index+1}}  {{item}}</li>
        </ul>
    </div>
    <script src='./vue.js'></script> 
    <script>
    var vm = new Vue({
        el:'#app',
        data: {
            mens:["Xiao Yi","Xiao Jie","Xiao Miao","puppy","Meow"],
            currentIndex:""
        }
     })
    </script>
    
Conditional judgment
  1. v-if is used to operate the DOM tree. If you don't know whether to display it or display it once, you usually use v-if

    <div id='app'>
        <button @click="isShow=!isShow">Sign in</button>
        <div v-if="isShow"> // Render when isShow is true
          user:<input type="text"><br>
          password:<input type="password">
        </div>
    </div>
    
  2. Use of v-esle-is

    <div id='app'>
        <h4 v-if="score>=90">excellent</h4>
        <h4 v-else-if="score>=80">good</h4>
        <h4 v-else-if="score>=60">pass</h4>
        <h4 v-else>fail,</h4>
        <button @click="sub">score-10</button>
    </div>
     
    <script>
    var vm = new Vue({
    el:'#app',
    data: {
      score:99
    },
    methods: {
      sub(){
        this.score = this.score -10;
     	 }
      }
    })
    </script>
    
  3. V-show operates display. If you need to switch between display and hiding frequently, use v-show

    <h2 v-show="true">{{message}}</h2>  // Show when isShow is true
    
  4. Small case of switching

    <div id='app'>
        <span v-if="isUser">
          <label for="username">User account</label>
          <input type="text" id="username" placeholder="User account">
        </span>
        <span v-else>
          <label for="email">User mailbox</label>
          <input type="text" id="email" placeholder="User mailbox">
        </span>
        <br>
        <button @click="isUser = !isUser">Login mode</button>
    </div>
    
  5. input box reuse problem

    • When switching the login mode, if the content is entered, after switching, it is found that the text still displays the previously entered content

    • This is because Vue takes performance into consideration when rendering DOM, and will reuse existing elements as much as possible instead of re creating new elements.

    • If we don't want Vue to have similar reuse problems, we can add keys to the corresponding input and ensure that the keys are different

      <div id='app'>
          <span v-if="isUser">
            <label for="username">User account</label>
            <input type="text" id="username" placeholder="User account">
          </span>
          <span v-else>
            <label for="email">User mailbox</label>
            <input type="text" id="email" placeholder="User mailbox">
          </span>
          <br>
          <button @click="isUser = !isUser">Login mode</button>
        </div>
      
Loop traversal
  1. Traversal array

    <ul>
      <li v-for="(item,index) in list">{{index}} --- {{item}}</li>
    </ul>
    
  2. Traversal object

    <ul>
       <li v-for="(item,key,index) in people"> {{index}} -- {{key}} --  {{item}} </li>
    </ul>
    
  3. Key can be bound with a kye when looping. At that time, the value of key must be unique, which is conducive to diff algorithm and improve performance. You can also make the key and item correspond one by one. It is recommended not to use index as the value of the key.

    <ul>
      <li v-for="item in list" :key="item">{{item}}</li>
    </ul>
    
splice method
  1. Insert element

    var list = ["Xiao Yi","Xiao Jie","little cat","puppy","Xiao Hong"]
    
    //After the first element, insert an element, ["Xiaoyi", "Phelps", "Xiaojie", "Kitty", "puppy", "Xiaohong"]
    list.splice(1,0,"Phelps")
    
  2. Replace element

    var list = ["Xiao Yi","Xiao Jie","little cat","puppy","Xiao Hong"]
    
    // Starting from the first element, replace two elements and enter a name ["Xiao Yi", "Phelps", "puppy", "Xiao Hong"]
    list.splice(1,2,'Phelps') 
    
    // Starting from the first element, replace two elements and enter two names ["Xiao Yi", "Phelps", "Liu Xiang", "puppy", "Xiao Hong"]
    list.splice(1,2,'Phelps','Liu Xiang') 
    
    // Starting from the first element, replace two elements, enter three names, [Xiao Yi "," Phelps "," Liu Xiang "," Yao Ming "," puppy "," Xiao Hong "], replace two elements and insert one element
    list.splice(1,2,'Phelps','Liu Xiang',"Yao Ming") 
    
  3. Delete element

    var list = ["Xiao Yi","Xiao Jie","little cat","puppy","Xiao Hong"]
    
    list.splice(1,3)	// Starting from the first element, delete three elements ["Xiaoyi", "Xiaohong"]
    list.splice(1)		// Start with the first element and delete all the following elements ["Xiaoyi"]
    
Array response method
  1. Array response method

    • splice() insert / delete / replace

    • push() adds a value after the array

    • unshift() adds a value before the array

    • pop() deletes the last element of the array

    • shift() deletes the first element of the array

    • sort() sorts the array

    • reverse() inverts the array

      <script>
          var list = [1, 22, 3, 4]
          list.splice(1, 2) //  Starting from the first element, delete 2 elements [1,4]
          list.splice(1, 0, 88) //Starting with the first element, insert an element [1, 88, 22, 3, 4]
          list.splice(1, 3, 66) //Starting from the first element, replace the following three elements with 66 [1, 66]
      
          list.push(66) //Insert an element [1, 22, 3, 4, 66] after the array
          list.unshift(88) //Insert an element before the array [88,1,22,3,4]
      
          list.pop() //Delete the last element of the array [1, 22, 3]
          list.shift()  //Delete the first element of the array [22, 3, 4]
      
          list.sort() // Sort the array
      
          list.reverse()  //Invert array [4, 3, 22, 1]
      </script>
      
  2. If you change the array through the index of the array, there will be no response (list.(index) = "aa"), which can be replaced by splice

    var list = ["a","b","c"]
    list[0] = "aa" //The data changes, but the view does not change ["aa", "b", "c"] 
    //Responsive
    list.splice(0,1,'aaa')//When the data changes, the view also changes ["aaa", "b", "c"]
    console.log(list) 
    
v-model bidirectional data binding
Bidirectional binding
  1. v-model can only be used in the input form. Two way binding means that if the value message in the binding changes, the value value in the input will also change. On the contrary, if the value value in the input changes, the bound message will also change

    <div id='app'>
      <input type="text" v-model="message">
      {{message}}
    </div>
    
    <script>
      var vm = new Vue({
        el:'#app',
        data: {
          message:"helloWorld"
        }
      })
    </script>
    
  2. Principle analysis of Vue model bidirectional binding: v-model is actually a combination of v-bind and v-on

    • v-bind binds a value attribute
    • The v-on instruction binds an input event to the current element
    <div id='app'>
        <!-- <input type="text" :value="message" @input="valueChange"> -->
        <input type="text" :value="message" @input="message = $event.target.value">
        {{message}}
    </div>
    
    <script>
      var vm = new Vue({
        el:'#app',
        data: {
          message:"hello World"
        },
        methods: {
          valueChange(event){
            this.message = event.target.value
          }
        }
       })
    </script>
    
v-model combined with ridio practice radio box
  1. The radio box is implemented in the form of ordinary html, and the radio box can be implemented only when the name attribute is the same

    <label for="male">
      male<input type="radio" id="male" name="sex">
    </label>
    <label for="female">
      female<input type="radio" id="male" name="sex">
    </label>
    
  2. When implementing the selection box with v-model, bind a variable (sex),

    • Select gender radio box

      <div id='app'> 
          <label for="male">
            male<input type="radio" id="male" value="male" v-model="sex">
          </label>
          <label for="female">
            female<input type="radio" id="male" value="female" v-model="sex">
          </label>
          <br>
          {{sex}}
      </div>
      
      data: {
         sex: ""
      }
      
v-model implementation of checkBox multi selection box
  1. To implement the agreement protocol, v-model binds a variable

    <label for="license">
      <input type="checkbox" id="license" v-model="agree">Consent agreement
    </label>
    <br>
    What do you choose:{{agree}}
    <button :disabled="!agree">next</button>
    
    data: {
       agree: false
    }
    
  2. Implement multiple check boxes

    • If the data bound by v-model is an array, click to add an element to the array

    • If the data bound by v-model is an object, click to select all (true) or none (false)

      <label for="">
        <input type="checkbox" value="Xiao Yi" v-model="people">Xiao Yi
        <input type="checkbox" value="" v-model="people">Jia Qiang
        <input type="checkbox" value="Yingjie" v-model="people">Yingjie
        <input type="checkbox" value="Jia bin" v-model="people">Jia bin
      </label>
      <br>
      The bound data is an array:{{people}}
      <br>
      <label for="">
        <input type="checkbox" value="Xiao Yi" v-model="people1">Xiao Yi
        <input type="checkbox" value="Jia Qiang" v-model="people1">Jia Qiang
        <input type="checkbox" value="Yingjie" v-model="people1">Yingjie
        <input type="checkbox" value="Jia bin" v-model="people1">Jia bin
      </label>
      <br>
      The bound data is Boolean:{{people1}}
      
      data: {
          people: [],
          people1:true,
        }
      
v-model combined with select
  1. Single choice: only one value can be selected

    • v-model binds a variable

    • When we select one of the options, we will assign the value of this option to this variable

      <select v-model="Myselect">
        <option value="English">English</option>
        <option value="Math">mathematics</option>
        <option value="art">Fine Arts</option>
      </select>
      What is your choice:{{Myselect}}
      
      data: {
        Myselect:"English"
      }
      
  2. Multiple selection: multiple values can be selected

    • v-model is bound to an array

    • Add a property in the select: multiple

      <select v-model="Myselects" multiple>
        <option value="English">English</option>
        <option value="Math">mathematics</option>
        <option value="art">Fine Arts</option>
      </select>
      What is your choice:{{Myselects}}
      
      data: {
        Myselects:[]
      }
      
Value binding in input
  1. Get a set of data, and then get it through v-for, v-bind and v-model

    <div id='app'>
    <label v-for="item in citys":for="item">
      <input type="checkbox" 
      :value="item" 
      :id="item" 
      v-model="myselect">
      {{item}}
    </label>
    <br>
    The selected city is:{{myselect}}
    </div>
    <script src='./vue.js'></script>
    <script>
    var vm = new Vue({
     el:'#app',
     data: {
      citys:["Beijing","Shanghai","Shenzhen","Hong Kong","Macao","Tibet"],
       myselect:[]
     }
    })
    </script>
    
v-model modifier
  1. js

    • lazy in the input box. Enter before updating the value in input to data

    • Number the number entered in the input box will become a string by default. You can add a number modifier, and the entered number will not become a string

    • trim, remove the spaces at both ends of the ending

      <div id='app'>
          <!-- lazy  -->
          <input type="text" v-model.lazy="message">
          <h2>{{message}}</h2>
      
          <!-- number -->
          <input type="number" v-model.number="age">
          <h2>{{age}}----{{typeof age}}</h2>
      
          <!-- trim -->
          <input type="text" v-model="say">
          <h2>{{say}}</h2>
      </div>
      <script src='./vue.js'></script>
      <script>
          var vm = new Vue({
          el:'#app',
          data: {
            message:"Write something",
            age:12,
            say:"Please do not enter spaces"
      	    }
          })
      </script>
      

Tags: Javascript Vue Vue.js

Posted by IMP_TWI on Sat, 14 May 2022 13:40:34 +0300