vue实例的生命周期1

 

 

 

 

13.1  <span id="top">生命周期图</span>

​   Vue实例的生命周期中有多个状态。

![生命周期图](./images/lifecycle.png)

> 测试代码

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue实例的生命周期</title>

    <!-- 引入vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <h1>测试生命周期</h1>
        <div>{{msg}}</div>
        <hr>
        <h3>测试beforeUpdate和update两个钩子函数</h3>
        <button @click="handlerUpdate">更新数据</button>
    </div>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                msg:"12345"
            },
            methods: {
                handlerUpdate:function(){
                    this.msg=this.msg.split("").reverse().join("");
                },
            },//按照示意图依次调用
            beforeCreate:function(){
                console.log("调用了beforeCreate钩子函数");
            },
            created:function () {
                console.log("调用了created钩子函数");
            },
            beforeMount: function () {
                console.log('调用了beforeMount钩子函数')
            },
            mounted: function () {
                console.log('调用了mounted钩子函数')
            },
            beforeUpdate: function () {
                console.log("调用了beforeUpdate钩子函数")
            },
            updated: function () {
                console.log("调用了updated钩子函数");
            },
            beforeDestroy: function () {
                console.log("调用了beforeDestroy钩子函数")
            },
            destroyed: function () {
                console.log("调用了destroyed钩子函数");
            },
        });
    </script>
</body>
</html>
```
 
> 1. 调用了beforeCreate钩子函数
> 2. 调用了created钩子函数
> 3. 调用了beforeMount钩子函数
> 4. 调用了mounted钩子函数

点击更新数据后:

`12345`变成了`54321`,此时调用了:

> 1. 调用了beforeUpdate钩子函数
> 2. 调用了updated钩子函数

打开F12控制台
直接输入`app.$destroy()`主动销毁Vue实例调用:

>1. 调用了beforeDestroy钩子函数
>2. 调用了destroyed钩子函数
posted @ 2021-05-02 11:04  好吗,好  阅读(36)  评论(0)    收藏  举报