Vue life cycle (the hook function)

Life cycle

Examples of lifecycle hook

Vue each instance when it is created to go through a series of initialization process - for example, the need for data monitoring, compiling templates, examples will be mounted to the DOM and DOM updates when the data changes. Some will also run in this process is called the life cycle of the hook function, which gives the user the opportunity to add your own code at different stages.

Such createdhooks may be used to execute code after one instance is created:

new Vue({
  data: {
    a: 1
  },
  created: function () {
    // `this` 指向 vm 实例
    console.log('a is: ' + this.a)
  }
})
// => "a is: 1"

There are also some other hook is invoked at different stages of the life cycle of the instances, such as mounted, updatedand destroyed. Lifecycle hook thiscontext points to call its Vue instance.

Do not use the option in the property or callback arrow functions , such as created: () => console.log(this.a)or vm.$watch('a', newValue => this.myMethod()). Because there is no arrow and function this, thiswill always find a lexical scope variables to their superiors, until you find, often resulting in Uncaught TypeError: Cannot read property of undefined, or Uncaught TypeError: this.myMethod is not a functionlike errors.

Lifecycle icon

The following figure shows the life cycle instance. You do not immediately understand everything, but as you continue to learn and use, its reference value will be higher.

Vue instance life cycle

<div id="app">
    {{ msg }}
</div>
<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            msg: 'hi vue'
        },
        // 在实例初始化之后,数据观测(data observer)和 event/watcher事件配置之前调用;
        beforeCreate: function () {
            console.log('beforeCreate')
        },
        /* 在实例创建完成后立即调用
        在这一步,实例已完成以下的配置:数据观测(data observer),属性和方法的用算,watch/event事件的回调。
        然而挂载的阶段还没开始,$el 属性目前不可见
        */
        created: function () {
            console.log('created')
        },
        // 在挂载开始之前调用:相关渲染的函数首次被调用
        beforeMount: function () {
            console.log('beforeMount')
        },
        // el 被创建的vm.$el替换,挂载成功
        mounted: function () {
            console.log('mounted')
        },
        // 数据更新时调用
        beforeUpdate: function () {
            console.log('beforeUpdate')
        },
        // 组件dom已经更新, 组件更新完毕
        updated: function () {
            console.log('updated')
        }
    });

    // 设置过期时间
    setTimeout(function () {
        vm.$data.msg = "change ....."
    }, 3000);
</script>

View more life cycle parameters: https: //cn.vuejs.org/v2/api/#beforeCreate

Life-cycle approach

beforeCreate

  • Type :Function

  • Details :

    After initialization example, it is called before the observed data (data observer) and event / watcher event configuration.

  • Reference : Life Cycle icon

created

  • Type :Function

  • Details :

    在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前不可见。

    发送ajax 实现数据驱动视图

  • 参考生命周期图示

beforeMount

  • 类型Function

  • 详细

    在挂载开始之前被调用:相关的 render 函数首次被调用。

    该钩子在服务器端渲染期间不被调用。

  • 参考生命周期图示

mounted

  • 类型Function

  • 详细

    el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子。如果 root 实例挂载了一个文档内元素,当 mounted 被调用时 vm.$el 也在文档内。

    • 虚拟dom Recat

    • 获取真实DOM

    注意 mounted 不会承诺所有的子组件也都一起被挂载。如果你希望等到整个视图都渲染完毕,可以用 vm.$nextTick 替换掉 mounted

    mounted: function () {
      this.$nextTick(function () {
        // Code that will run only after the
        // entire view has been rendered
      })
    }

    该钩子在服务器端渲染期间不被调用。

  • 参考生命周期图示

beforeUpdate

  • 类型Function

  • 详细

    数据更新时调用,发生在虚拟 DOM 打补丁之前。这里适合在更新之前访问现有的 DOM,比如手动移除已添加的事件监听器。

    该钩子在服务器端渲染期间不被调用,因为只有初次渲染会在服务端进行。

  • 参考生命周期图示

updated

  • 类型Function

  • 详细

    由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。

    当这个钩子被调用时,组件 DOM 已经更新,所以你现在可以执行依赖于 DOM 的操作。然而在大多数情况下,你应该避免在此期间更改状态。如果要相应状态改变,通常最好使用计算属性watcher 取而代之。

    注意 updated 不会承诺所有的子组件也都一起被重绘。如果你希望等到整个视图都重绘完毕,可以用 vm.$nextTick 替换掉 updated

    updated: function () {
      this.$nextTick(function () {
        // Code that will run only after the
        // entire view has been re-rendered
      })
    }

    该钩子在服务器端渲染期间不被调用。

  • 参考生命周期图示

activated

deactivated

beforeDestroy

  • 类型Function

  • 详细

    实例销毁之前调用。在这一步,实例仍然完全可用。

    该钩子在服务器端渲染期间不被调用。

  • 参考生命周期图示

destroyed

  • 类型Function

  • 详细

    Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。

    关闭定时器

    该钩子在服务器端渲染期间不被调用。

  • 参考生命周期图示

errorCaptured

2.5.0+ 新增

  • 类型(err: Error, vm: Component, info: string) => ?boolean

  • 详细

    当捕获一个来自子孙组件的错误时被调用。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回 false 以阻止该错误继续向上传播。

    你可以在此钩子中修改组件的状态。因此在模板或渲染函数中设置其它内容的短路条件非常重要,它可以防止当一个错误被捕获时该组件进入一个无限的渲染循环。

    错误传播规则

    • By default, if the global config.errorHandleris defined, all errors will still send it, so these errors will still report to a single local analysis services.
    • If there are multiple inheritance or a parent slave link assembly errorCapturedhooks, one by one, they will evoke the same error.
    • If the errorCapturedhook itself throws an error, and this error was originally captured the new error will be sent to the global config.errorHandler.
    • A errorCapturedhook can return falseto prevent the error continues to spread upwards. Essentially saying "get this error has been and should be ignored." It will prevent any other will be evoked this error errorCapturedhook and global config.errorHandler.

Life cycle (the hook function)

beforeCreate(){

    // 组件创建之前

    console.log(this.msg);

},

created(){

    // 组件创建之后

    // 使用该组件,就会触发以上的钩子函数,created中可以操作数据,发送ajax,并且可以实现vue==》页面的影响  应用:发送ajax请求

    console.log(this.msg);

    // this.msg = '嘿嘿黑';

},

beforeMount(){

    // 装载数据到DOM之前会调用

    console.log(document.getElementById('app'));

},

mounted(){

    // 这个地方可以操作DOM

    // 装载数据到DOM之后会调用 可以获取到真实存在的DOM元素,vue操作以后的DOM

    console.log(document.getElementById('app'));

},

beforeUpdate(){

    // 在更新之前,调用此钩子,应用:获取原始的DOM

    console.log(document.getElementById('app').innerHTML);

},

updated(){

    // 在更新之前,调用此钩子,应用:获取最新的DOM

    console.log(document.getElementById('app').innerHTML);

},

beforeDestroy(){

    console.log('beforeDestroy');

},

destroyed(){

    console.log('destroyed');

},

activated(){

    console.log('组件被激活了');

},

deactivated(){

    console.log('组件被停用了');

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <App></App>
</div>

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

    let Test = {
        data: function () {
            return {
                msg: 'alex',
                count: 0,
                timer: null
            }
        },
        template: `
            <div>
                <p>{{ count }}</p>
                <div id="box">{{ msg }}</div>
                <button v-on:click="changeHandler">修改</button>
            </div>
        `,
        methods: {
            changeHandler: function () {
                this.msg = 'wusir';
                document.querySelector('#box').style.backgroundColor('red')
            }
        },
        beforeCreate() {
            // 组件创建之前
            console.log('组件创建之前', this.msg);
        },

        created() {
            // 重要****
            // 组件创建之后
            // 使用该组件,就会触发以上的钩子函数,created中可以操作数据,发送ajax,并且可以实现vue==》页面的影响  应用:发送ajax请求
            console.log('组件创建之后', this.msg);
            this.timer = setInterval(() => {
                this.count++
            }, 1000);
            // this.msg = '嘿嘿黑';
        },
        beforeMount() {
            // 装载数据到DOM之前会调用
            console.log(document.getElementById('app'));
        },

        mounted() {
            // 这个地方可以操作DOM
            // 装载数据到DOM之后会调用 可以获取到真实存在的DOM元素,vue操作以后的DOM
            console.log(document.getElementById('app'));
        },

        beforeUpdate() {
            // 在更新之前,调用此钩子,应用:获取原始的DOM
            console.log(document.getElementById('app').innerHTML);
        },

        updated() {
            // 在更新之前,调用此钩子,应用:获取最新的DOM
            console.log(document.getElementById('app').innerHTML);
        },
        beforeDestroy() {
            console.log('beforeDestroy');
        },

        destroyed() {
            // 定时器的消耗在此方法处理 关闭清楚
            console.log('destroyed',this.timer);
            clearInterval(this.timer);
        },

        activated() {
            console.log('组件被激活了');
        },

        deactivated() {
            console.log('组件被停用了');
        }
    };

    let App = {
        data: function () {
            return {
                isShow: true
            }
        },
        template: `
            <div>
                 <keep-alive>
                    <Test v-if="isShow"/>
                </keep-alive>
                <button @click="clickRemove">改变test组件的生死</button>
            </div>
        `,
        methods: {
            clickRemove: function () {
                this.isShow = !this.isShow
            }
        },
        components: {
            Test
        }
    };

    let vm = new Vue({
        el: '#app',
        data: function () {
            return {}
        },
        components: {
            App
        }
    })
</script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/Hybb/p/12108268.html