Vue实例的生命周期(钩子函数)

Vue实例的生命钩子总共有10个

先上官方图:

下面时一个vue实例定义钩子函数的例子:

var app=new Vue({
    el:'#app',
    beforeCreate:function(){
        console.log('1-beforeCreate 初始化之后');
    },
    created:function(){
        console.log('2-created 创建完成');
    },
    beforeMount:function(){
        console.log('3-beforeMount 挂载之前');
    },
    mounted:function(){
        console.log('4-mounted 被创建');
    },
    beforeUpdate:function(){
        console.log('5-beforeUpdate 数据更新前');
    },
    updated:function(){
        console.log('6-updated 被更新后');
    },
    activated:function(){
        console.log('7-"keep-alive"中组件被激活时');
    },
    deactivated:function(){
        console.log('8-"keep-alive"中组件被停用时');
    },
    beforeDestroy:function(){
        console.log('9-beforeDestroy 销毁之前');
    },
    destroyed:function(){
        console.log('10-destroyed 销毁之后')
    }
})
activated和deactivated上面的图没有,这个时vue的<keep-alive></keep-alive>才能触发钩子,而keep-alive是保存组件内部状态的一种做法

而keep-alive的基本使用方法也简单:
<keep-alive>
   <router-view></router-view>
</keep-alive>

这样,切换前端路由后组件的数据就保存下来

 

posted @ 2018-02-03 14:06  张啊咩  阅读(232)  评论(0编辑  收藏  举报