Vue中的声明周期钩子函数

何为生命周期

每个Vue实例在被创建时总要经过一系列的初始化过程:创建实例、装载模板、渲染模板等等。Vue为生命周期中的每个状态都设置了钩子函数(监听函数)。每当Vue实例处于不同的生命周期时,对应的函数就会被触发调用。

图为Vue官方文档提供的生命周期图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

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

    <div id="app">
        
        <span id="num">{{num}}</span>
        
        <button @click="num++">赞!!!</button>

        <h2>{{name}},有{{num}} 个人点赞</h2>

    </div>

    <script>
        var vue = new Vue({
            el: "#app",
            data: {
                name: "张三",
                num: 100
            },
            methods: {
                show() {
                    return this.name;
                },
                add() {
                    this.num++
                }

            },

            beforeCreate() {
                console.log("=============beforeCreate========");
                console.log("数据模型未加载:" + this.name,this.num);
                console.log("方法未加载: "+ this.show());
                console.log("html模板未加载:" + document.getElementById("num"));

            },
            created() {
                console.log("=============beforeCreate========");
                console.log("数据模型已加载:" + this.name,this.num);
                console.log("方法已加载: "+ this.show());
                console.log("html模板已加载:" + document.getElementById("num"));
                console.log("html模板未渲染:" + document.getElementById("num").innerText);
            },
            beforeMount() {
                console.log("=============beforeMount========");
                console.log("html模板未渲染:" + document.getElementById("num").innerText);
            },
            mounted() {
                console.log("=============mounted========");
                console.log("html模板已渲染:" + document.getElementById("num").innerText);
            },
            beforeUpdate() {
                console.log("=============beforeUpdate========");
                console.log("数据模型已更新:" + this.num);
                console.log("html模板未更新:" + document.getElementById("num").innerText)
            },
            updated() {
                console.log("===updated===")
                console.log("数据模型已更新:" + this.num)
                console.log("html模板已更新" + document.getElementById("num").innerText)
            },
        })
    </script>
    
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值