VUE生命周期变化

366 阅读1分钟

概述

本文主要是描述vue加载、销毁过程中数据的初始化过程,以及父子组件,路由跳转在创建,销毁时的先后顺序。

data,method访问

代码

<template>
    <div class="index-demo"></div>
</template>
<script>
export default {
    name: 'indexDemo',
    data () {
        return {
            origin: 'origin',
        }
    },
    methods: {
        init () {
            console.log('init methods');
        },
    },
    beforeCreate () {
        try {
            console.warn('beforeCreatethis.data.origin', this.origin);
            console.warn('beforeCreatethis.method.init');
            this.init();
        } catch (e) {
            console.warn('beforeCreate error', e);
        }
    },
    created () {
        try {
            console.warn('created this.data.origin', this.origin);
            console.warn('created this.method.init');
            this.init();
        } catch (e) {
            console.warn('created error', e);
        }
    }
}
</script>

结果

结论

data 和 method在生命周期created时可以访问

父子组件加载、销毁生命周期

父组件代码

<template>
    <div class="father">
        <child></child>
    </div>
</template>
<script>
import child from '@components/child.vue';

export default {
    name: 'father',
    
    components: {
        child
    },

    beforeCreate () {
        console.warn('father beforeCreated');
    },
    created () {
        console.warn('father created');
    },
    beforeMount () {
        console.warn('father beforeMount');
    },
    mounted () {
        console.warn('father mounted');
    },
    beforeDestroy () {
        console.warn('father beforeDestory');
    },
    destroyed () {
        console.warn('father destroyed');
    }
}
</script>

子组件

<template>
    <div class="child">
        
    </div>
</template>
<script>
export default {
    name: 'child',
    beforeCreate() {
        console.warn('child beforeCreated')
    },
    created() {
        console.warn('child created')
    },
    beforeMount() {
        console.warn('child beforeMount')
    },
    mounted() {
        console.warn('child mounted')
    },
    beforeDestroy(){
        console.warn('child beforeDestory')
    },
    destroyed() {
        console.warn('child destroyed');
    }
}
</script>

** 运行** 创建过程

销毁过程

猜想

因为在created时父组件的datamethods已经可以访问,此时子组件进行初始化加载,就不会出现报错,并且可以根据父组件传递过来的数据进行对应操作,并且访问父组件数据。 销毁过程也是类似。

路由跳转过程中两个页面的生命周期变化

father作为其中一个页面,定义另一个页面为other

other 代码

<template>
  <div class="other"></div>
</template>
<script>
export default {
  name: 'other',
    beforeCreate () {
      console.warn('other beforeCreated');
    },
    created () {
        console.warn('other created');
    },
    beforeMount () {
        console.warn('other beforeMount');
    },
    mounted () {
        console.warn('other mounted');
    },
    beforeDestroy () {
        console.warn('other beforeDestory');
    },
    destroyed () {
        console.warn('other destroyed');
    }
}
</script>

路由跳转结果

结论

暂不清楚这个顺序是为啥,容我查查先