1. Life cycle

The so-called life cycle refers to the process of life from birth to death. The Vue lifecycle refers to the process from creation to destruction of a Vue instance. This process is often accompanied by self-calls to functions called hook functions.

Life cycle diagram: official diagram


Common hook functions in the VUE lifecycle:

The method name Interpretation of the
beforeCreate El has no binding scope, no data, no methods, and so on
created The data attribute and related methods in methods have been initialized, but the page has not been rendered
beforeMount El is scoped, but there is no real data on the page yet
mounted The data has been rendered to the page
beforeUpdate Data is called when data is updated, while the old data is still on the page
updated Data Is called when data is updated. At this point, the page is already filled with updated data
beforeDestroy Called before destruction, when data, methods, and so on have not been destroyed
destroyed Destroy call! Kill them all!

The lifecycle of a Vue is obvious, just remember that the method for retrieving data before rendering is called in Created (). For example, if the background administrator successfully logs in to the user management page and needs to display user information, the following command can be used:

 created() {
    this.init(a); }, methods: {// Initialize method
    init() {
      // Initiates an asynchronous request to obtain user information
    },
Copy the code

2. Calculate properties

We know that we can display values in the data property through interpolation, such as {{username}}.

However, sometimes we need to combine multiple attributes in data for display, such as displaying the total math score of all students in a certain class, when we can use the calculated attributes.

Computing attributes can cache the data, which greatly improves access efficiency.

Computed attributes are written in computed in the VUE instance:

<script>
 const app = new Vue({
    el: '#app',
    data: {
        msg:"I love you China"
    },
    methods: {

    },
    computed:{

    }
 });
</script>
Copy the code

2.1 Case 1: Display full name

<div id ="app"</div> <script SRC ="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
 const app = new Vue({
    el: '#app',
    data: {
        firstName: "Elon" ,
        lastName: "马斯克 "
    },
    methods: {

    },
    computed:{
        fullName(){
            return this.firstName+"."+this.lastName; }}}); </script>Copy the code

Running results:

2.2 Case 2: Show the overall score

<div id ="app"> 
  <span v-for="(student, index) in students" :key="student.id"> {{index}} {{student.score}} <br> </span> totalScore: {{totalScore}} </div> <script SRC ="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
 const app = new Vue({
    el: '#app',
    data: {
        students:[
            {id:1,name:"Xiao Ming",score:100},
            {id:2,name:"Little red",score:200},
            {id:3,name:"Chou",score:300}
        ]
    },
    methods: {

    },
    computed:{
        totalScore(){
            return this.students.reduce((sum,student)=>{ return sum + student.score },0); }}}); </script>Copy the code

Running results:

3. The listener

  • Key words: Watch
  • Used to listen for changes in data
  • The listening property must already exist for data

case

<div id ="app"> 
    <input type="text" v-model="name" > 
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
 const app = new Vue({
    el: '#app',
    data: {
       name: "Zhang Wuji"
    },
    methods: {

    },
    computed:{

    },
    watch:{
        name(newValue){
            console.log("Changed name :"+newValue); }}}); </script>Copy the code

Running results:

4. The filter

  • Key words: filters
  • Used for common text formatting
  • Instead of changing the value of the data property, change the result after rendering
  • You can use it in two places: {{}} and the V-bind expression
  • The filter must have a return value

Example: Formatting time

<div id="app"> < span > format before: {{time}} < / span > < br > < span > after formatting: {{time | timeFormat}} < / span > < / div > < script SRC ="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  const app = new Vue({
      el: '#app',
      data: {
          time: "August 22, 2021"
      },
      methods: {
      },
      filters: {
          timeFormat(time){
              if(time.indexOf("Year") != - 1){time = time.replace(/ year /,"-");
              }
              if(time.indexOf("Month") != - 1){time = time.replace(/ month /,"-");
              }
              if(time.indexOf("Day") != - 1){time = time.replace(/ day /,"");
              }
              returntime; }}}); </script>Copy the code

Running results:

5. axios

  • Axios is an asynchronous request technique for making asynchronous requests on a page
  • Automatically convert JSON data
  • Through CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code

5.1 Get request

5.11 No Parameters

axios.get('http://localhost/api/user').then(function(res){ 
  All data is stored in the data property of the RES
  console.log(res.data)
})
Copy the code

5.12 to? The form of the pass parameter

axios.get('http://localhost/api/user? id=10').then(function(res){ 
   All data is stored in the data property of the RES
  console.log(res.data)
})
Copy the code

5.13 ReSTUL Parameter Transfer

axios.get('http://localhost/api/user/1234').then(function(res){ 
  All data is stored in the data property of the RES
  console.log(res.data)
})
Copy the code

5.14 Parameter Transfer in Params format

axios.get('http://localhost/api/user', {params: {
        id: 123
      }).then(function(res){ 
  All data is stored in the data property of the RES
  console.log(res.data)
})
Copy the code

5.2 a Post request

axios.post('http://localhost/api/user', {
      id: 123,
      typeId: 1234
}).then(function(res){
 All data is stored in the data property of the RES
  console.log(res.data)
})
Copy the code

5.3 Global Configuration

5.3.1 Configuring a Common Request Header

axios.defaults.baseURL = 'https://localhost/api';
Copy the code

After configuring the common request header, the axios request path can be abbreviated:

axios.get('/user').then(function(res){ 
  All data is stored in the data property of the RES
  console.log(res.data)
})
Copy the code

5.3.2 Configuring the Timeout Period

axios.defaults.timeout = 1000;
Copy the code

5.4 the interceptor

  • Request interceptor: Performs some operations before the user initiates a request, such as adding tokens to all request headers
  • Response interceptor: Takes some action after receiving the response
# 1. Request interceptor: Set token globally
axios.interceptors.request.use(function (config) {
  let token = sessionStorage.getItem('token')
  if (token) {
    config.headers['token'] = token
  }
  return config
})
#2. Response interceptor
axios.interceptors.response.use(function(res) {
  var data = res.data;
  return data;
}, function(err){

})
Copy the code

5.5 async and await

Sometimes a business needs to call multiple interfaces at a time, and the latter interface depends on the results of the previous interface call. If the former interface fails, the latter will be completely destroyed. For example:

axios.get('http://localhost/api/user').then(function(res){ 
   if(res.data.success){
       axios.get('http://localhost/api/data').then(function(res){ 
        if(res.data.success){ ...... }})}})Copy the code

The above example is in nesting, the code experience is not very good, so we introduced async and await.

Async is placed before a function as a keyword to indicate that the function is an asynchronous function, which means that the execution of the function does not block the execution of subsequent code. Such as:

async getUser(){

}
Copy the code

To await means to wait for the following code to finish and return a result. Await can be followed by any expression and is non-blocking.

Use async and await together:

async getUser(){
  let result = await axios.get('http://localhost/api/user');
  if(result.data.success){
    let typeId = result.data.typeId;
    let type = await axios.get('http://localhost/api/getType? typeId='+typeId); . }}Copy the code

Does this look better?!

6. Common operations on arrays

6.1 Returning the array length

   var arr= [1.12.8.30];
   var len = arr.length;
   console.log(len);// The result is 4
Copy the code

6.2 Merging arrays into Strings

  var arr= [1.12.8.30];
  var str = arr.join(",");
  console.log(str)
Copy the code

Print result:

6.3 Adding Elements: Push and unshift

  • Push is adding elements to the end of an array
  • Unshift adds elements to the array header
 var arr = [1.12.8.30];
 arr.push(99);
 arr.unshift(100);
 console.log(arr);
Copy the code

Print result:

6.4 Replacing elements: splice

  • The first argument, the index of the element to be replaced. Note: Array subscripts start at 0
  • Second argument: The number of elements to replace, starting with the first index
  • Third parameter: What to replace with
 var arr = [1.12.8.30];
 arr.splice(2.1."66");
 console.log(arr);
Copy the code

Print result:

6.5 Deleting Elements: POP and splice

  • Pop is the last element removed from the array
  • Splice deletes elements based on their subscript. The first argument is the initial coordinate of the element to be deleted. The second argument is the number of elements to be deleted
var arr = [1.12.8.30];
arr.pop();/ / delete 30
arr.splice(0.1);/ / delete 1
console.log(arr);
Copy the code

Print result:

6.6 Array In Reverse order

var arr = [1.12.8.30];
arr.reverse();
console.log(arr);
Copy the code

Print result:

6.7 Filter Criteria The new array filter is returned

 var arr = [1.12.8.30];
 const newArr = arr.filter(item => item >2);
 console.log(arr);
 console.log(newArr);
Copy the code

Print result:

6.8 Merging Multiple Arrays: concat

var a = [1.12.8.30];
var b = [Awesome!.777];
var c = a.concat(b);
console.log(c);
Copy the code

Print result:

6.9 Returning the specified array: slice

  • Slice does not change the value of the original array
  • First argument: the initial coordinates of the array to return
  • Second argument: Returns the number of array elements
var arr = [1.12.8.30];
var newArr = arr.slice(0.2);
console.log(arr);
console.log(newArr);
Copy the code

Print result: