Basic knowledge of VUE iii

  1. Vue component life cycle
  2. The use of axios
  3. Refs,refs, refs,nextTick usage and name usage

The human life cycle

The entire process of a component from creation to destruction is the life cycle

Vue_ life cycle

Hook function

VueFramework-built functions are executed automatically as the component lifecycle phases

Function: Perform a specific operation at a specific point in time

Scenario: After the component is created, an Ajax request can be made in the Created lifecycle function to initialize the data data

Classification: 4 major stages and 8 methods

  • Initialize the
  • mount
  • update
  • The destruction
phase The method name The method name
Initialize the beforeCreate created
mount beforeMount mounted
update beforeUpdate updated
The destruction beforeDestroy destroyed

Official document

The following figure shows the life cycle of the instance. You don’t have to understand everything immediately, but it will become more valuable as you learn and use it.

Initialization phase

Master the function and execution timing of two hook functions in initialization phase

Explanation of meaning:

1. New Vue() — Vue instantiation (the component is also a small Vue instance)

2.Init Events & Lifecycle – Initializes Events and Lifecycle functions

3. BeforeCreate — The lifecycle hook function is executed

4.Init Injections&reActivity — Add data and methods inside Vue

5. Created – Lifecycle hook functions are executed and instances are created

6. Next comes the compile template phase — start the analysis

7.Has el option? – Is there an EL option – Check where to hang it

No. Call the $mount() method

Yes, continue checking the template option

Components/life.vue – Create a file


<script>
export default {
    data(){
        return {
            msg: "hello, Vue"}},// init
    // After new Vue(), some attributes and methods are added to the instance object inside the Vue. Data and methods are initialized "before".
    beforeCreate(){
        console.log("BeforeCreate -- Execute");
        console.log(this.msg); // undefined
    },
    // Data and methods are initialized
    // Scenario: network request, register global event
    created(){
        console.log("Created -- implemented");
        console.log(this.msg); // hello, Vue

        this.timer = setInterval(() = > {
            console.log("Ha ha ha.");
        }, 1000)}}</script>
Copy the code

App.vue – Introduction to use

<template>
  <div>
    <h1>1. Life cycle</h1>
 	<Life></Life>
  </div>
</template>

<script>
import Life from './components/Life'
export default {
  components: {
    Life
  }
}
</script>
Copy the code

Mount the stage

Master the function and execution time of two hook functions in mount stage

Explanation of meaning:

1. Check the template option

Compiling template returns the render function

None – Compile el option tag as template(template to render)

2. Before mounting the virtual DOM to the real DOM

BeforeMount – Life cycle hook functions are executed

4. Create… Attach the virtual DOM and rendered data to the real DOM

5. The real DOM is mounted

Mounted – The lifecycle hook function is executed

Components/life.vue – Create a file

<template>
  <div>
      <p>Learn the life cycle - watch console print</p>
      <p id="myP">{{ msg }}</p>
  </div>
</template>

<script>
export default {
    / /... Omit other code
    
    // Mount
    // Before the actual DOM is mounted
    // Scenario: Preprocesses data without triggering the updated hook function
    beforeMount(){
        console.log("BeforeMount -- execute");
        console.log(document.getElementById("myP")); // null

        this.msg = "Revalue"
    },
    // After the actual DOM is mounted
    // Scenario: Real DOM after mounting
    mounted(){
        console.log("Mounted");
        console.log(document.getElementById("myP")); // p}}</script>
Copy the code

Update the stage

Master the functions and execution timing of two hook functions in update stage

Explanation of meaning:

1. Update DOM before data changes in data

BeforeUpdate – The lifecycle hook function is executed

3. The Virtual DOM… – The virtual DOM is re-rendered and patched to the real DOM

4. Updated — The lifecycle hook function is executed

5. When data changes – repeat the cycle

Components/life.vue – Create a file

Prepare ul+ Li loop, button add element, trigger data change -> cause the update cycle to start

<template>
  <div>
      <p>Learn the life cycle - watch console print</p>
      <p id="myP">{{ msg }}</p>
      <ul id="myUL">
          <li v-for="(val, index) in arr" :key="index">
              {{ val }}
          </li>
      </ul>
      <button @click="arr.push(1000)">Click add value at the end</button>
  </div>
</template>

<script>
export default {
    data(){
        return {
            msg: "hello, Vue".arr: [5.8.2.1]}},/ /... Omit other code

    // Update
    // Prerequisite: data is executed only when the data changes
    // Before the update
    beforeUpdate(){
        console.log("BeforeUpdate -- execute");
        console.log(document.querySelectorAll("#myUL>li") [4]); // undefined
    },
    // After the update
    // Scenario: Get the updated real DOM
    updated(){
        console.log("Updated -- Executed");
        console.log(document.querySelectorAll("#myUL>li") [4]); // li}}</script>
Copy the code

Destruction of phase

Grasp the functions and execution timing of two hook functions in the destruction phase

Explanation of meaning:

1. When $destroy() is called — such as when the component DOM is removed (example v-if)

BeforeDestroy – The lifecycle hook function is executed

3. Remove the data monitor, subcomponents, and event listeners

4. After the instance is destroyed, a hook function is finally triggered

5. Destroyed — Lifecycle hook functions are executed

Components/life.vue – Preparing the lifecycle method (Life component is about to be removed)

<script>
export default {
    / /... Omit other code
    
    // destroy
    // Prerequisite: V-if ="false" destroys the Vue instance
    // Scenario: Remove global event, remove current component, timer, timer, eventBus remove event $off method
    beforeDestroy(){
        // console.log('beforeDestroy -- execute ');
        clearInterval(this.timer)
    },
    destroyed(){
        // console.log("destroyed -- executed ");}}</script>
Copy the code

Main: app.vue – Click the button to remove the Life component from the DOM -> Causes the Life component to enter the destruction stage

<Life v-if="show"></Life>
<button @click="show = false">Destruction of the component</button>

<script>
    data(){
        return {
            show: true}},</script>
Copy the code

axios

Axios is basically used

Axios document

The characteristics of

  • Supports Ajax requests sent by clients
  • Support server node.js to send requests
  • Support Promise related usage
  • Interceptor functionality that supports request and response
  • Automatically convert JSON data
  • The underlying IMPLEMENTATION of AXIos is still a native JS implementation, encapsulated internally by Promise

Basic use of Axios

axios({
  method: 'Request mode'.// get post
  url: 'Requested address'.data: {    // Concatenate the parameters to the request body, the parameters of the POST request
    xxx: xxx,
  },
  params: {  // Concatenate parameters to the request line, parameters of the GET request
   	xxx: xxx 
  }
}).then(res= > {
  console.log(res.data) // The result returned by the background
}).catch(err= > {
  console.log(err) // The background error message is returned
})

Copy the code

Basic use of Axios – get data

Call document end _ Get all book information interface

Function: Click call background interface, get all the data – print to the console

Interface: look at the documentation then

Import: Download Axios before you can use it

Effect:

Examples are as follows:

components/UseAxios.vue

<template>
  <div>
    <p>1. Access to all book information</p>
    <button @click="getAllFn">Click - to view the console</button>
  </div>
</template>

<script>
// Goal 1: Get all book information
1. Download axios
// 2. Introduce axios
// 3. Initiate an AXIos request
import axios from "axios";
export default {
  methods: {
    getAllFn() {
      axios({
        url: "http://123.57.109.30:3006/api/getbooks".method: "GET".// The default is GET request, can be omitted
      }).then((res) = > {
        console.log(res);
      });
      // axios()- get the Promise object in place}}};</script>
Copy the code

Axios basically uses – parameter passing

Call interface – Get information about a book

Function: Click to call the background interface, query the user wants the book information – print to the console

Interface: read the documentation

Effect:

Examples are as follows:

components/UseAxios.vue

<template>
  <div>
    <p>2. Query information about a book</p>
    <input type="text" placeholder="Please enter the name of your enquiry" v-model="bName" />
    <button @click="findFn">The query</button>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      bName: ""
    };
  },
  methods: {
    / /... All code for querying is omitted
    findFn() {
      axios({
        url: "/api/getbooks".method: "GET".params: { // Will metro Axios eventually concatenate to the URL? behind
            bookname: this.bName
        }
      }).then(res= > {
          console.log(res); })}}};</script>
Copy the code

Axios basically uses – publishing books

Complete the function of publishing books

Function: click the new button, the user input book information, transfer to the background – print the results in the console

Interface: look at the documentation then

Examples are as follows:

components/UseAxios.vue

<template>
  <div>
    <p>3. Add book information</p>
    <div>
        <input type="text" placeholder="Title" v-model="bookObj.bookname">
    </div>
    <div>
        <input type="text" placeholder="The author" v-model="bookObj.author">
    </div>
    <div>
        <input type="text" placeholder="Publishing house" v-model="bookObj.publisher">
    </div>
    <button @click="sendFn">release</button>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      bName: "".bookObj: { // The parameter name is matched with the parameter name in the background
          bookname: "".author: "".publisher: ""}}; },methods: {
    / /... Other code is omitted
    sendFn(){
       axios({
           url: "/api/addbook".method: "POST".data: {
               appkey: "7250d3eb-18e1-41bc-8bb2-11483665535a". this.bookObj// same as the following
            // bookname: this.bookObj.bookname,
            // author: this.bookObj.author,
            // publisher: this.bookObj.publisher}})}},};</script>
Copy the code

Axios basic use – global configuration

Avoid prefix base addresses, expose them in logical pages, and set them uniformly

axios.defaults.baseURL = "http://123.57.109.30:3006"

// The url prefix for all requests can be removed, and axios will automatically concatenate baseURL's address in front of the request
getAllFn() {
    axios({
        url: "/api/getbooks".method: "GET".// The default is GET request, can be omitted
    }).then((res) = > {
        console.log(res);
    });
    // axios()- get the Promise object in place
},
Copy the code


n e x t T i c k and NextTick and
Refs knowledge

$refs – access to the DOM

Using ref and $refs can be used to get DOM elements

components/More.vue

<template>
  <div>
      <p>1. Get native DOM elements</p>
      <h1 id="h" ref="myH">I'm a lonely, pathetic, edible H1</h1>
  </div>
</template>

<script>
// Target: Get the component object
// 1. Create component/import component/register component/use component
// 2. Alias the component ref
// 3. When appropriate, get the component object
export default {
    mounted(){
        console.log(document.getElementById("h")); // h1
        console.log(this.$refs.myH); // h1}}</script>

<style>

</style>
Copy the code

Summary: Native DOM tags can be obtained by id/ref

$refs- Gets the component object

Get the component object and call the method in the component

components/Child/Demo.vue

<template>
  <div>
      <p>I'm a Demo component</p>
  </div>
</template>

<script>
export default {
    methods: {
        fn(){
            console.log("Method called in demo component"); }}}</script>
Copy the code

More.vue – Gets the component object – calls the component method

<template>
  <div>
      <p>1. Get native DOM elements</p>
      <h1 id="h" ref="myH">I'm a lonely, pathetic, edible H1</h1>
      <p>2. Get the component object - callable everything within the component</p>
      <Demo ref="de"></Demo>
  </div>
</template>

<script>
// Target: Get the component object
// 1. Create component/import component/register component/use component
// 2. Alias the component ref
// 3. When appropriate, get the component object
import Demo from './Child/Demo'
export default {
    mounted(){
        console.log(document.getElementById("h")); // h1
        console.log(this.$refs.myH); // h1

        let demoObj = this.$refs.de;
        demoObj.fn()
    },
    components: {
        Demo
    }
}
</script>
Copy the code

Conclusion: ref defines the value, and the component object can be retrieved by the $refs. value, and then the variables within the component can be called

$nextTick use

Vue updates DOM- asynchronously

Click count++, and immediately get the tag content through the “native DOM”, without getting the new value

components/Move.vue

<template>
  <div>
      <p>1. Get native DOM elements</p>
      <h1 id="h" ref="myH">I'm a lonely, pathetic, edible H1</h1>
      <p>2. Get the component object - callable everything within the component</p>
      <Demo ref="de"></Demo>
      <p>3. Vue updates DOM asynchronously</p>
      <p ref="myP">{{ count }}</p>
      <button @click="btn">Click count+1 to immediately extract the p tag content</button>
  </div>
</template>

<script>
// Target: Get the component object
// 1. Create component/import component/register component/use component
// 2. Alias the component ref
// 3. When appropriate, get the component object
import Demo from './Child/Demo'
export default {
    mounted(){
        console.log(document.getElementById("h")); // h1
        console.log(this.$refs.myH); // h1

        let demoObj = this.$refs.de;
        demoObj.fn()
    },
    components: {
        Demo
    },
    data(){
        return {
            count: 0}},methods: {
        btn(){
            this.count++; // start a DOM update queue (asynchronous task)
            console.log(this.$refs.myP.innerHTML); / / 0

            // Cause: Vue updates DOM asynchronously
            This.$nextTick()
            // Process: DOM updates trigger function bodies in $nextTick one by one
             this.$nextTick(() = > {
                console.log(this.$refs.myP.innerHTML); / / 1})}}}</script>
Copy the code

Summary: Because DOM updates are asynchronous

$nextTick Usage scenario

Click the search button, a focused input box pops up, and the button disappears

components/Tick.vue

<template>
  <div>
      <input ref="myInp" type="text" placeholder="This is an input field." v-if="isShow">
      <button v-else @click="btn">Click me to search</button>
  </div>
</template>

<script>
// Target: Click button (disappear) - Input box appears and focuses
// 1. Get the input box
// 2. The input box calls the event method focus() to achieve the focus behavior
export default {
    data(){
        return {
            isShow: false}},methods: {
        async btn(){
            this.isShow = true;
            // this.$refs.myInp.focus()
            // Cause: Data changes update DOM asynchronously
            // The input box is not yet mounted to the real DOM
            / / address:
            // this.$nextTick(() => {
            // this.$refs.myInp.focus()
            // })
            // Extension: await instead of callback functions
            $nextTick() returns a Promise object in place
            await this.$nextTick()
            this.$refs.myInp.focus()
        }
    }
}
</script>
Copy the code

Component name property

Component names can be registered with the value of the component’s name property

Question: Are component names not arbitrary?

Answer: The component we encapsulate – we can define the component name for the name property – gives the user a consistent prefix style

components/Com.vue

<template>
  <div>
      <p>I am a Com component</p>
  </div>
</template>

<script>
export default {
    name: "ComNameHaHa" // You can define your own name when registering
}
</script>
Copy the code

App.vue – Register and use

<template>
  <div>
    <h1>1. Life cycle</h1>
    <Life v-if="show"></Life>
    <button @click="show = false">Destruction of the component</button>
    <hr>
    <h1>2. Use axios</h1>
    <UseAxios></UseAxios>
    <hr>
    <h1>3. Use of $refs</h1>
    <More></More>
    <hr>
    <h1>4. $nextTick usage scenario</h1>
    <Tick></Tick>
    <hr>
    <h1>5. The name property in the component object</h1>
    <ComNameHaHa></ComNameHaHa>
  </div>
</template>

<script>
import Life from './components/Life'
import UseAxios from './components/UseAxios'
import More from './components/More'
import Tick from './components/Tick'
import Com from './components/Com'
export default {
  data(){
    return {
      show: true}},components: {
    Life,
    UseAxios,
    More,
    Tick,
    [Com.name]: Com // If the key in the object is a variable, the expression of the property name is []
    // "ComNameHaHa": Com}}</script>
Copy the code