Vue -- 09 life cycle and Ajax server communication

Posted by jumpfroggy on Wed, 03 Nov 2021 07:28:14 +0100

Vue -- 09 life cycle and Ajax server communication

9.1 Vue instance lifecycle

Lifecycle hook function

  Each Vue instance goes through a series of initialization processes when it is created

The life cycle is divided into three stages: initializing the display, updating the display, and destroying Vue instances

Hook function in initialization phase:

beforeCreate() before instance creation: neither data nor template was obtained

After the created() instance is created: data can be accessed at the earliest, but the template is not obtained

beforeMount() before data mounting: the template has been obtained, but the data is not mounted on the template.

mounted() after data mounting: the data has been mounted in the template

Hook function in update phase:

beforeUpdate() template update: before data changes, update the data template before calling.

updated() after the template is updated: render the data into the data template

Hook function in destruction phase:

beforeDestroy() before instance destruction

After the destroyed() instance is destroyed

 

Lifecycle diagram

DEMO

<body>
    <div id="app">
        <h1>{{ msg }}</h1>
    </div>
    <script src="./node_modules/vue/dist/vue.js"></script>
    <script>
        var vm = new Vue({
            //el: '#app',
            data: {
                msg: 'heloo'
            },

            beforeCreate() {
                console.log('beforeCreate()', this.$el, this.$data)
            },
            created() {
                // Initialized data Data, but the data is not mounted in the template
                console.log('created()', this.$el, this.$data)
            },
            beforeMount() {
                // The template was obtained, but the data was not mounted on the template
                console.log('beforeMount()', this.$el, this.$data)
            },
            mounted() {
                // The compilation is completed and the data has been mounted in the template
                console.log('mounted()', this.$el, this.$data)
            },
            beforeUpdate() {
                // When data After changing, update the data in the template before calling.
                // Note: browser problem, need to use this.$el.innerHTML Get pre update Dom Template data
                console.log('beforeUpdate()', this.$el.innerHTML, this.$data)
            },
            updated() {
                // data cover Vue After rendering Dom Data template
                console.log('updated()', this.$el.innerHTML, this.$data)
            },
            beforeDestroy() {
                console.log('beforeDestroy');
            },
            destroyed() {
                console.log('destroyed');
            }


        }).$mount('#app'); // Not used in instance el Options, available with $mount()Manual mount Dom

        // vm.$destroy() Destroy Vue example
    </script>
</body>

 

9.2 liveServer server plug-in

1. Install the liveServer server plug-in in VS Code for Ajax interface calls

2. Start the server:
Method 1: open any html page, and you can see GoLive at the bottom. Click start. The default port is 5500
Method 2: right click the html page and click the following to access the page
Note: if you have started the server before, use mode 2 to start the html page. If you cannot use mode 1, the port will be occupied

3. Change the default port number of liveServer:
Press Ctrl + to open Settings. Open settings.json as follows,
Add "liveserver. Settings. Port" to the json file: 8080,

 

9.3 ajax libraries commonly used in Vue

At present, Vue officials do not have any built-in ajax request methods
1 vue-resource
In the vue1.x version, Vue resource, an unofficial Vue plug-in, is widely used
2 axios
In the vue 2 + version, it is officially recommended to use a great third-party ajax request library

Use: obtain data in combination with the life hook and render the data (created)

 

9.4 use of Vue resource

Reference Manual: https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

NPM installation command:   npm install vue-resource  

<body>
    <div id="app">
        <ul>
            <li v-for="(item,index) in msg" :key="index">{{item.name}}</li>
        </ul>
    </div>

    <script src="./node_modules/vue/dist/vue.js"></script>
    <script src="./node_modules/vue-resource/dist/vue-resource.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                msg: []
            },
            created() {
                this.$http.get('http://127.0.0.1:5500/vue-07-lifecycle&ajax/db.json').then((response) => {
                    // If you want to use Vue Instance this,You need to use the arrow function here
                    // success callback
                    console.log(response.data) // Response data
                    this.msg = response.data
                }, (response) => {
                    // error callback
                    console.log(response.statusText) //error message
                })
            }
        });

    </script>
</body>

 

9.5 use of Axios

Reference Manual: https://github.com/axios/axios/blob/master/README.md

npm install command: npm install axios

<body>
    <div id="app">
        <ul>
            <li v-for="(item,index) in msg" :key="index">{{item.name}},{{item.age}}</li>
        </ul>
    </div>

    <script src="./node_modules/vue/dist/vue.js"></script>
    <script src="./node_modules/axios/dist/axios.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                msg: []
            },
            created() {
                axios.get('http://127.0.0.1:5500/vue-07-lifecycle&ajax/db.json').then(response => {
                    console.log(response.data) // Get the returned result data
                    this.msg = response.data
                }).catch(error => {
                    console.log(error.message)
                })
            }
        });
    </script>
</body>

 

9.6 componentized axios communication

Add axios asynchronous access to the Bootstrap case in the previous chapter

Install NPM: NPM install Axios

Introduce axios.js  

<script src="../node_modules/axios/dist/axios.js"></script>

emp.json

[
{"id": 1, "name": "Zhang San 1", "salary": 9899},
{"id": 2, "name": "Zhang San 2", "salary": 9999},
{"id": 3, "name": "Zhang San 3", "salary": 9099},
{"id": 4, "name": "Zhang San 4", "salary": 9199}
]

Refactoring AppHome.js

; (function () {

    const template = ` <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">

    <!--Upper right area-->
    <!--<h1 class="page-header">Dashboard</h1>-->
    <!--Define slot-->
    <slot name="dashboard"></slot>
    <dash-board :hobbies='hobbies' @del-Hobby="deleteHobby"></dash-board>

    <!--Lower right area-->
    <h2 class="sub-header">Section title</h2>
    <home-list :empList='empList' :delItem="delItem"></home-list>
  </div>`;

    window.AppHome = {
        template,
        components: {
            DashBoard,
            HomeList
        },
        data() {
            return {
                hobbies: ['read a book', 'Billiards', 'sleep', 'Lu code'],//dashboard Display data
                empList: []
            };
        },
        created() {
            axios.get('http://127.0.0.1:5500/vue-07-lifecycle&ajax/04-bootstrap-ajax/emp.json').then(response => {
                console.log(response.data) // Get the returned result data
                this.empList = response.data
            }).catch(error => {
                console.log(error.message)
            })
        },
        methods: {
            // Deletes the data of the specified subscript
            // Because delete emp Yes empList Do the update operation,
            // and empList It is initialized in the current component, so the deleted function should be defined in this component
            delItem(index) {
                this.empList.splice(index, 1);
            },
            deleteHobby(index) {
                this.hobbies.splice(index, 1);
            }
        }
    }

})()

 

Topics: Vue