Vue.js之Vue实例的生命周期

本文主要介绍Vue.js中实例创建到销毁的整个生命周期,通过下面这个小案例进行演示。

Vue实例默认会先执行四个函数,分别是创建前、已创建、挂载前和已挂载函数。当点击案例中的第一个按钮时,数据会发生变化,更新前及已更新对应的函数会被执行。当点击案例中的第二个按钮时,Vue实例被销毁,销毁前及已销毁对应的函数会被执行

具体说明:(通过debugger打断点更易理解)

beforeCreate会在实例data等创建前进行调用,此时访问data中的数据,会是undefined。created会在数据创建后执行,可以访问data中的数据,此时数据还未被渲染至页面上。beforeMount在挂载前执行,此时可对data中的数据作最后一次修改。mounted在数据挂载之后执行.当更新数据时,beforeUpdate会先执行,此时更新的数据还未被渲染至页面上。updated在数据更新完成后执行,此时页面已渲染了最新的数据。删除实例时,会先执行beforeDestroyed,此时方法和数据都未删除。destroyed在删除之后执行,此时方法等失效,但数据可以访问。

效果如图:

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div v-text="msg"></div>
        <div><button @click="update">点击更新</button></div>
        <div><button @click="destroy">点击销毁</button></div>
    </div>
    <script src="./vue.min.js"></script>
    <script>
        let vu = new Vue({
            el: '#app',
            data: {
                msg: 'default'
            },
            methods: {
                update: function() {
                    this.msg = 'changed'
                },
                destroy: function() {
                    this.$destroy();
                }
            },
            beforeCreate: function() {
                console.log('创建前');
            },
            created: function() {
                console.log('已创建');
            },
            beforeMount: function() {
                console.log('挂载前');
            },
            mounted: function() {
                console.log('已挂载');
            },
            beforeUpdate: function() {
                console.log('更新前');
            },
            updated: function() {
                console.log('已更新');
            },
            beforeDestroy: function() {
                console.log('销毁前');
            },
            destroyed: function() {
                console.log('已销毁');
            }
        })
    </script>
</body>

</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值