Vue 实例_生命周期

2018-09-28  本文已影响0人  牛耀
  1. vue对象的生命周期
    1). 初始化显示
    • beforeCreate()
    • created()
    • beforeMount()
    • mounted()
      2). 更新显示:this.xxx = value
    • beforeUpdate()
    • updated()
      3). 销毁vue实例: vm.$destory()
    • beforeDestory()
    • destoryed()
  2. 常用的生命周期方法
    mounted(): 发送ajax请求, 启动定时器等异步任务
    beforeDestory(): 做收尾工作, 如: 清除定时器
HTML:
<div id="test">
    <button @click="destroyVM">destroy vm</button>
    <p v-show="isShow">Vue实例的生命周期</p>
    <p>{{isShow}}</p>
    <p>{{isShow}}</p>
    <p>{{isShow}}</p>
    <p>{{isShow}}</p>
</div>
new Vue({
        el: '#test',
        data: {
            isShow: true
        },
        // 1、初始化阶段
        beforeCreate(){
            console.log('beforeCreate()');
        },
        created(){
            console.log('created()');
        },
        beforeMount(){
            console.log('beforeMount()');
        },
        mounted(){// 初始化显示之后立即调用(1次)
            console.log('mounted()');
            this.intervalId = setInterval(() => {
                console.log('-------->');
                this.isShow = !this.isShow;// 更新数据
            }, 1000);
        },
        // 2、更新阶段
        beforeUpdate(){
            console.log('beforeUpdate()');
        },
        updated(){
            console.log('updated()');
        },
        // 3、死亡阶段
        beforeDestroy(){// 死亡之前调用(1次)
            console.log('beforeDestroy()');
            // 清除定时器
            clearInterval(this.intervalId);
        },
        destroyed(){
            console.log('destroyed()');
        },
        methods: {
            destroyVM(){
                // 干掉VM
                this.$destroy();
            }
        }
    })
上一篇 下一篇

猜你喜欢

热点阅读