Do not compare with others, but beyond their own, to cry to cry out tears of excitement, to laugh out of growth character!Copy the code

Main Contents of this issue

  1. Binding style:
  2. Custom instruction
  3. Calculate attribute
  4. The filter
  5. axios
  6. ***** Vue life cycle

I. Binding style:

  1. Bind inline style to the style property:

    When: When you want to change the value of a CSS property exactly

  2. Bind the class attribute:

    (1). When: Modify multiple CSS property values in a batch

    (2). Bad way: Treat the entire class as a normal string property binding

    Disadvantages: Extremely inconvenient to modify one of the classesCopy the code

    (3) good ways: 2 ways:

    A. Execute a variable for each class that can change dynamically

    < element :class="{class name 1: bool expression or variable, class name 2: bool expression or variable}" 2). Principle: when newVue() scans here for the first time, or when dependent variables change I. Evaluate the bool expression or variable after each class name ii. If the bool expression or variable after each class name is true, the class appears in effect on the final element -- light iii. If a bool expression or variable value following the class name is false, the class does not appear on the final element and does not work! Example: Verify that the mobile phone number format is correct -- with CSS styleCopy the code

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"></script> <style> /* Verify that the style */. Success {border:1px solid green; background-color:lightGreen; color:green; padding:3px 10px; font-size:12px; } /* Failed to validate the style */. Fail {border:1px solid red; background-color:pink; color:red; padding:3px 10px; font-size:12px; } </style> </head> <body> <div id="app"> <! 1. Input content - phone Stores the mobile phone number entered by the user.""2. Span class-success stores a bool indicating whether the authentication is successfulfalse3. Span contents - errMsg Stores the prompt messages to be displayed in the SPAN.""-- > <! As long as the user enters something in the input, the validation is triggered, so bind the onINPUT event and execute vali to validate the new content in the text box --> < INPUT V-model ="phone" @input="vali"> <! If the user does not enter content in the text box, no class is applied at all --> <! -- Enable SUCCESS class only if the user enters content in the text box and the verification result passes. Disable FAIL otherwise enable Fail Class if the user enters content in the text box and the verification result fails. Disable SUCCESS --> < SPAN :class="{ success:phone.trim()! ==''&&success==true, fail:phone.trim()! ==''&&success==false }">{{errMsg}}</span>
  </div>
  <script>
    new Vue({
      el:"#app"// Data :{phone:"",
        success:false,
        errMsg:""}, // Because the interface needs a function methods:{vali(){ console.log(this.phone); Var reg=/^1[3-9]\d{9}$/; var reg=/^1[3-9]\d{9}$/; Var result=reg.test(this.phone.trim()); var result=reg.test(this.phone.trim()); // If the contents of phone are emptyif(this.phone.trim()===""){// Clear the contents of this. ErrMsg ="";
          }else if(result==true){// Otherwise, if the validation succeeds: // change the success variable totrueThis. Success =true; // Modify the errMsg variable to the phone number format correctly this.errMsg="Correct format of mobile phone number";
          }else{// Otherwise if validation fails: // change the success variable tofalse, indicating that the authentication failed this.success=false; // Change the errMsg variable to the phone number format incorrectly this.errMsg="Mobile phone number format is incorrect"; }}}}) </script> </body> </ HTML >Copy the code

B. Specify a variable object for the entire class. A variable object contains multiple dynamically changing classes

1).< element :class=” variable name “>

Data :{variables :{class1:true or false, class2:true or false}}Copy the code

2). Example: Modify the above example with a class variable:

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"></script> <style> .msg{ padding:3px 10px; font-size:12px; } /* Verify the style */. Success {border:1px solid green; background-color:lightGreen; color:green; } /* Failed to validate the style */. Fail {border:1px solid red; background-color:pink; color:red; } </style> </head> <body> <div id="app"> <! 1. Input content - phone Stores the mobile phone number entered by the user.""2. Span class = span class = span class = span class = span class = span class = span class = span class = span class = span class = span class = span class = span class = spanfalse, fail:false} 3. Span contents - errMsg Stores the prompt messages to be displayed in the span.""-- > <! As long as the user enters something in the input, the validation is triggered, so bind the onINPUT event and execute vali to validate the new content in the text box --> < INPUT V-model ="phone" @input="vali"> <! -- new method, do not make any judgment in HTML --> <span class="msg" :class="spanClass">{{errMsg}}</span>
  </div>
  <script>
    new Vue({
      el:"#app"// Data :{phone:"",
        spanClass:{
          success:false// All lights fail:false, // All lights off}, errMsg:""}, // Because the interface needs a function methods:{valiVar reg=/^1[3-9]\d{9}$/; var reg=/^1[3-9]\d{9}$/; Var result=reg.test(this.phone.trim()); var result=reg.test(this.phone.trim()); // If the contents of phone are emptyif(this.phone.trim()===""){// Clear the contents of this. ErrMsg =""; This. SpanClass ={success:false, fail:false}}else if(result==true){// Otherwise if the validation passes: // Modify spanClass to successtrueAnd change the value of fail tofalse
            this.spanClass={ success:true, fail:false}; // Modify the errMsg variable to the phone number format correctly this.errMsg="Correct format of mobile phone number";
          }else{// Otherwise if the validation fails: // Modify the SUCCESS value in spanClass tofalseAnd change the value of fail totrue
            this.spanClass={ success:false, fail:true}; // Change the errMsg variable to the phone number format incorrectly this.errMsg="Mobile phone number format is incorrect"; }}}}) </script> </body> </ HTML >Copy the code

(4). If an element has both invariant classes and dynamically changing classes :< element class=” fixed classes “:class=” possible dynamically changing classes “> Eventually the two classes are merged into a single class, which applies to the element.

Ii. Custom instruction:

  1. When: You want to do some DOM initialization on elements when the page loads:

    For example: get focus automatically

  2. How about: 2 steps

    (1). Add a custom directive to Vue home

    Directive (" directive name ",{// Do not use the v- prefix! Postinserted (domElem){//domElem automatically takes the DOM element object with the current directive and performs some DOMe-related initialization on the current DOM element object domElem, Like getting focus}})Copy the code

    (2). Using custom instructions:

    < element v-custom directive name > // Emphasize that custom directives must be prefixed with v-!

  3. Results:

    (1).new Vue() when scanning here for the first time, it will go to Vue’s home to find if there is a custom attribute with the same name.

    (2). If found, the insert () function of the custom instruction is automatically called, and the CURRENT DOM element object with the custom instruction is passed to the first inserted() parameter.

    (3). Within the INSERTED () callback, the actions performed on the current DOM element are reflected to the page.

  4. Example: Using a custom directive, let the text box automatically get focus:

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"></script> <script> // Add a new directive to the vue family: my-focus vue. Directive ("my-focus"Inserted (domElem){domelem.focus (); // While the current element is inserted on the page, the current element is self-assigned to get focus(domElem){domelem.focus (); }}) </script> </head> <body> <div id="app"> <! 1. Vue does not define a directive for elements to automatically get focus 2. Focus (), <input v-my-focus><button> </button> < div> <script> new vue ({el:"#app"}) </script> </body> </ HTML >Copy the code

Iii. Computational Attributes:

  1. What it means: you don’t actually save the value of an attribute, but each time you use an attribute, you dynamically calculate the result based on the dependent variable and apply it to the page.

  2. When: If an attribute value is not readily available and requires a complex calculation process to obtain, use computed attributes

  3. How to:

(1). Add new members to new Vue() :

new Vue({ el:"#app", data:{ ... }, methods:{event handlers}, computed:{save computed attributes attribute name (){return dynamically calculates new attribute values based on other variables}}})Copy the code

(2). Using calculated attributes:

< element >{{attribute name}}</ element > // Calculate attribute use must not add ()!

  1. Question: Since it is a function, why not put it in methods?

    A: Because ordinary functions placed in methods perform complex calculations again each time they are called, the results are not cached and reused by VUE.Copy the code
  2. Advantages of calculating attributes:

The result of the first calculation is cached by vUE, and the calculation will not be repeated even if the calculation attribute is used repeatedly. Unless the dependent variable changes, the recalculation is forced. But the new value is still cached and reused!

  1. Conclusion:

    A. In the future, if you focus on doing something and don’t care too much about the return value, use normal functions of Methods!

    B. Use computed attributes in the future if you are more focused on using the result value returned by the function

  2. Example: Using calculated properties to achieve shopping cart total price:

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"></script>
</head>
<body>
  <div id="app"> <! - want to display the shopping cart goods list and shopping cart price - > < h3 > total: selections {{total. ToFixed (2)}} < / h3 > < ul > < li v - for ="(p,i) of cart" :key="i"> {{p.p name}} | selections {{p.p. Rice toFixed (2)}} | {{p.c mount}} | selections {{(p.p rice * p.c mount). ToFixed (2)}} < / li > < / ul > < h3 > total price: Selections {{total. ToFixed (2)}} < / h3 > < / div > < script > new Vue ({el:"#app",
      data:{
        cart:[
          {pname:"Huawei", price:5588, count:2},
          {pname:"Millet", price:3588, count:3},
          {pname:The word "apple", price:8588, count:1},]}, methods:{}, computed:{// Because the total shopping cart price is not readily available, it needs a complex traversal process to calculate // Therefore, calculated attributes are used.total(){console.log(' called total() ') var result=0;for(var p of this.cart){
            result+=p.price*p.count;
          }
          returnresult; }}}) </script> </body> </ HTML >Copy the code

Iv. Filter:

  1. What is: a special function that displays the original value of a variable after processing it

  2. Why: Because some variable values are retrieved from the server and cannot be shown to people directly

    For example: date and time gender server side stores: milliseconds 1 and 0 people want to see: year month day hour minute second male and femaleCopy the code
  3. When: As long as the original value of the variable cannot be shown directly, it needs to be processed before it can be shown, the filter is used

  4. How about: 2 steps

    (1). Add filters to the VUE family

    ↓ vue. filter(" filter name ", function(oldVal){← out return according to the new value obtained after oldVal processing})Copy the code

    (2). Use the filter: element < > {{variable filter |}} < / element >

  1. Example: Use a filter to process gender 0 and 1 before displaying
<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"> < / script > < script > / / for all gender in the project process need to show again. / / in the future {{sex | sexFilter}} / / there were several possible oldVal: 0 or 1 / / left left Vue. Filter ("sexFilter".function(oldVal){
      return oldVal==1?"Male":"Female"
    })
  </script>
</head>
<body>
  <div id="app"Gender: 1 > < h3 > {{sex1}} < / h3 > < h3 > gender 2: {{sex2}} < / h3 > < h3 > gender 1: {{sex1 = = 1?"Male":"Female"</h3> <h3> sex2 :{{sex2==1?"Male":"Female"Gender}} < / h3 > < h3 > 1: {{sex1 | sexFilter}} < / h3 > < h3 > gender 2: {{sex2 | sexFilter}} < / h3 > < / div > < script > new Vue ({el:"#app", data: {sex1:1, sex2:0}}) < / script > < / body > < / HTML > run results:Copy the code

Var. Filter (" filter name ", function(oldVal, custom parameter){// oldVal (oldVal, custom parameter){// oldVal (oldVal, custom parameter){// oldVal (oldVal, custom parameter){// oldVal (oldVal, custom parameter){// oldVal (oldVal, custom parameter); : when using the filter element < > {{variable | filter (custom argument value)}} < / element >Copy the code
  1. Multiple filters can also post: element > < {{variable filter filter | 1 | 2 |… }} < / element >

Note: only the first filter can receive the original value of the variable. After that, all other filters receive not the original value, but the intermediate product of the previous neighboring filter

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"></script> <script>"sexFilter".function(oldVal, language type){// If the language type is passed in"English", Male Female is processedif(Language type =="English") {return oldVal==1?"Male":"Female"
      }else{// Otherwise if the language type passed in is not"English", the default processing of male and femalereturn oldVal==1?"Male":"Female"}}); / / in order to be able to give additional icon at the end of gender: / / may: {{sex | sexIcon}} 0 s and 1 s / / may: {{sex | sexFilter | sexIcon}} to male and female / / may: {{sex | sexFilter ("English") | sexIcon}} to Male and Female / / reserved Vue. Filter ("sexIcon".function(oldVal){// There can be 6 types of oldVal: 1 and 0 Male and Female // If oldVal is 1 or 0, return directly to ♂ and ♀if(oldVal==1){
        return "Came"
      }else if(oldVal==0){
        return "♀"
      }else if(oldVal=='male'||oldVal=="Male"Otherwise, if oldVal is not 0 or 1, join ♂ and ♀ to the end of the existing oldValreturn oldVal+"Came"
      }else{
        return oldVal+"♀"
      }
    })
  </script>
</head>
<body>
  <div id="app"Gender: 1 > < h3 > {{sex1 | sexIcon}} < / h3 > < h3 > gender 2: {{sex2 | sexIcon}} < / h3 > < h3 > gender 1: {{sex1 | sexFilter | sexIcon}} < / h3 > < h3 > gender 2: {{sex2 | sexFilter | sexIcon}} < / h3 > <! - custom - > < h3 > gender 1: {{sex1 | sexFilter ("English") | sexIcon}} < / h3 > < h3 > gender 2: {{sex2 | sexFilter ("English") | sexIcon}}</h3>
  </div>
  <script>
    new Vue({
      el:"#app", data: {sex1:1, sex2:0}}) < / script > < / body > < / HTML > run results:Copy the code

5. Axios:

  1. What is it: a promise based library dedicated to sending Ajax on all platforms

  2. Why: jQuery isn’t already $.ajax()

    In future framework development, jquery is hardly used. Just to send an Ajax request with a function called $.ajax(), it’s not worth importing a jQuery library of dozens or hundreds of functions!

    In the future, other non-jquery front-end frameworks will need a library dedicated to sending Ajax requests.

  3. When: Use Axios whenever ajax requests are sent in vUE. But axios is not limited to vue, it can be used in regular web pages and even nodeJS

  4. How to:

    (1). Send get request:

    Axios.get (" server side interface address ", {params:{variable name: value,... :... }}).then(function(result){//.then (function(result){//.then (function(result){//.then (function(result){//.then) })Copy the code

    (2). Send a POST request:

    Axios. post(" server side interface address "," variable 1= value 1& variable 2= value 2&..." ). Then (function(result){//. Then (function(result){//. Then (function(result){//. })Copy the code
  5. Problem: Ajax requests are written in many places in the project, and it would be too much trouble to write the full path to the server-side interface starting with http:// each time!

  6. Solution: In fact, the domain name portion of most interfaces in a project is exactly the same.

    (1). Axios provides a place to save the domain name of the same part shared by all interfaces. Axios.defaults. baseURL=” http://base domain name”

    (2). When using AXIos to send a request, only write the relative path of the interface. When running, AXIos will automatically combine the saved basic domain name and the relative interface name into a complete interface address, and then send the request. Axios.get (“/ interface name “,…) .then(…)

  7. Example: Use AXIos to send three requests to the server interface of Dongge Sina Cloud Student Mall:

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/axios.min.js"></script> </head> <body> <script> // configure all interfaces with the same base domain name path part axios.defaults.baseurl ="http://xzserver.applinzi.com";
    axios.get("/index")
    .then(function(result){
      console.log(result.data);
    });
    axios.get("/details",{params:{lid:5} // Lid =5, add to end of url}).then(function(result){
      console.log(result.data);
    });
    axios.post(
      "/users/signin"."uname=dingding&upwd=123456"
    ).then(function(result){ console.log(result.data); }); </script> </body> </ HTML >Copy the code

  1. Axios.get ().then(function(){… })this->window, but from now on we want all this in new Vue() to refer to the current new Vue() object

  2. Solution: future

    axios.get().then(function(){ ... }) ↓ axios.get("/ interface name ",...) .then(reuslt=>{ ... })Copy the code

    Result: This in the.then() callback matches the external this!

Vue object life cycle:

  1. What is: the process that a VUe object goes through from creation until all page content is loaded

  2. Including: 4 stages:

    (1). You must create the create

    A. Create a new Vue() object. In the new Vue() object, create a data object and invite a bodyguard

    B. Do not scan the DOM tree, and there is no virtual DOM tree

    (2). You must mount the mount

    A. Scan the DOM tree, generate a virtual DOM tree, and mount data to page elements for the first time


Update Is triggered when a variable in data is modified

$destroy is also triggered when the $destroy function is called to destroy the current component. Why learn the lifecycle:

(1). In jquery, there are many initialization operations when the page is loaded for the first time, such as automatically sending Ajax requests, such as automatically binding the first screen data. All of these operations are written in(function(){… }), is automatically executed after the DOM content is loaded!

$(function(){$function(){$function(){$function(){$function(){$function(){$function(){$function(){$function(); }), such as the code that automatically sends ajax requests to get the first screen data?

(3). Error: Placing axios request code outside of new Vue().

Because future vUE adopts componentized development, it is stipulated that all JS code of a component must be placed inside the object of this component! No logically related code is allowed outside the component objectCopy the code

(4). Correct: the page initialization JS code to be executed, bound to a life cycle phase of the VUE, automatically executed!

  1. When: In the future, life cycles will be used whenever you want to automate some operations during vUE object creation and mounting

  2. How to: Vue objects have four life cycles, each preceded by a pair of (2) hook functions (callbacks)

BeforeCreate () triggers automatically before newVue() is created. Without data and variables, you can’t modify variables in data — not a good place to send first-screen Ajax requests

When new Vue() and data objects are created, a. You can manipulate variable B. in data, but cannot perform DOM-related operations because the DOM tree has not been scanned. BeforeMount () automatically triggers A. before starting to scan the DOM tree. You can also manipulate the variable b in data. However, you can't perform DOM related operations because you haven't scanned the DOM tree (2) yet. Mount () After the virtual DOM tree is created and the page content is mounted for the first time. Create a virtual DOM tree, and the data is displayed on the page, so you can perform DOM related operations. Mounted () is best for page initialization. BeforeUpdate () fires automatically before modifying variables in data. Update updated() Automatically triggered after modifying variables in data. BeforeDestroy () Automatically triggered before starting to destroy the current component. The Destroy phase destroy Destroyed () is automatically triggered after the current component is destroyedCopy the code

  1. Example: Demonstrates the four life cycles and eight hook functions of a Vue component

Note:

on the page must bind and use the Products variable in data to start the update phase
<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <script src="js/vue.js"></script>
  <script src="js/axios.min.js"></script> </head> <body> <! When you want the page to load, load the six commodities on the home page of the student shopping mall --> <div id="app">
    <ul>
      <li v-for="(p,i) of products" :key="i"> {{p.t itle}} | selections {{p.p rice}} | {{conviction yourself etails}} < / li > < / ul > < / div > < script > / / configuration axios. Defaults. BaseURL ="http://xzserver.applinzi.com";
    var vm=new Vue({
      el:"#app",
      data:{
        products:[]
      },
      methods:{
      },
      beforeCreate(){console.log(' automatically triggered before creating data:{} ')},created(){console.log(' automatically triggered after creating data:{} ')},beforeMount(){console.log(' automatically triggered before mounting page elements and content ')},mounted(){console.log(' automatically triggered when page elements and contents are mounted ') // To keep this in.then() consistent with the external this, both refer to the current new Vue() object axios.get()"/index"). Then (result=>{// want to return data to the products variable, this. Products =result.data; })},beforeUpdate(){console.log(' automatically triggered before modifying variables in data ')},updated(){console.log(' automatically triggered after changing variables in data ')},beforeDestroy(){console.log(' automatically triggered before destroying the current component ')},destroyed(){console.log(' automatically triggered after the current component is destroyed ')}}) // In the console: VM.$destory</script> </body> </ HTML >Copy the code