Vue 实例生命周期

一、生命周期

Vue 应用都是通过 Vue 实例(ViewModel)完成的,Vue 创建实例需要一系列的初始化动作,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。当然创建实例只是生命周期的一部分。

在 Vue 对象声明周期的每个阶段都会运行一些叫生命周期的钩子函数,在对应的钩子函数中,可以添加自己的代码以达到某种特定的功能。

钩子函数:

  • beforeCreate:Vue 实例初始化之后执行,但是此时 Vue 实例数据与 el 数据都为空
  • created:Vue 实例中的数据已经绑定,但是 el 为空
  • beforeMount:在 el 挂载之前执行
  • mounted:此时 el 已经被挂载到指定的 DOM 节点
  • beforeUpdate:Vue 实例数据更新之后执行,但是页面中的数据并没有更新
  • updated:页面数据更新之后执行
  • beforeDestroy:Vue 实例销毁之前执行
  • destroyed:实例销毁之后执行

二、代码演示

我们通过对应的钩子函数来说明 Vue 对象的生命周期,你可以拷贝下面的代码,在控制台观察运行结果

HTML 代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue实例_生命周期</title>
</head>
<body>
<div id="test">
    <p>更新次数:{{count}}</p>
    <button @click="destroyVue">destory vue</button>
</div>
</body>
</html>

Vue.js 代码

<!-- 引入本地的 Vue.js -->
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#test',
        data: {
            count: 0
        },

        beforeCreate() {
            console.log('beforeCreate()')
        },

        created() {
            console.log('created()')
        },

        beforeMount() {
            console.log('beforeMount()')
        },

        // 在挂载之后执行一个定时任务,不断地显示与隐藏 'Hello Vue.js'
        mounted() {
            console.log('mounted()')
            this.intervalId = setInterval(() => {
                // 更新 'count',触发 beforeUpdate() 与 updsted()
                this.count ++
            }, 1000)
        },

         beforeUpdate() {
            console.log('beforeUpdate() ' + this.count)
        },

        updated () {
            console.log('updated() ' + this.count)
        },

        // 在对象销毁之前,清除定时任务
        beforeDestroy() {
            console.log('beforeDestroy()')
            clearInterval(this.intervalId)
        },

        destroyed() {
            console.log('destroyed()')
        },

        // 给按钮绑定一个事件:销毁当前 Vue 对象
        methods: {
            destroyVue () {
                this.$destroy()
            }
        }
    })

</script>

PS:
常用的钩子函数:

  • mounted():用于发送 ajax 请求,启动定时任务等
  • beforeDestory():做一些收尾工作,用于清除定时任务等

猜你喜欢

转载自blog.csdn.net/codejas/article/details/80955118