今天看啥  ›  专栏  ›  哆啦C梦的百宝箱

Vue学习(26)生命周期

哆啦C梦的百宝箱  · 简书  ·  · 2022-03-11 15:36
<!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>生命周期</title>
</head>

<body>
    <div id="root">
        <div>n的值:{{n}}</div>
        <button @click="add">点我+1</button>
        <button @click="destory">点我销毁vm</button>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const vm = new Vue({
            el: '#root',
            data: {
                n: 1
            },
            watch:{
                n(){
                    console.log('n变了');
                }
            },
            methods: {
                add() {
                    console.log('add');
                    this.n++;
                },
                destory(){
                    console.log('bye');
                    this.$destroy();
                }
            },
            beforeCreate() {
                console.log('beforeCreate');
            },
            created() {
                console.log('created');
            },
            beforeMount() {
                console.log('beforeMount');
            },
            mounted() {
                console.log('mounted',this.$el instanceof HTMLElement);
            },
            beforeUpdate() {
                console.log('beforeUpdate');
                console.log(this.n);
            },
            updated() {
                console.log('updated');
            },
            beforeDestroy() {
                console.log('beforeDestroy');
            },
            destroyed() {
                console.log('destroyed');
            },
        });
    </script>
</body>

</html>
知识点

1:生命周期:Vue在关键时刻帮我们调用一些特殊名称的函数。
2:在beforeDestory中如果调用方法,你会看到控制台里面,方法的确执行了,但是页面没有更新。在destroyed中我们可以反问到data中的数据。
3:常用生命周期钩子:
①:mounted:发送ajax请求,启动定时器,绑定自定义事件,订阅消息等【初始化操作】
②:beforeDestroy:清除定时器,解绑自定义事件,取消消息订阅。【收尾工作】
4:关于销毁vm实例
①:销毁后,借助vue开发者工具,看不到任何消息。
②:销毁后,自定义事件会失效,原生dom事件依旧有效。
③:一般不会在beforeDestroy里面操作数据,因为即使操作数据,也不会触发更新流程了。




原文地址:访问原文地址
快照地址: 访问文章快照