美文网首页技术文章
vue父子组件&继承组件的生命周期

vue父子组件&继承组件的生命周期

作者: 5df463a52098 | 来源:发表于2018-04-15 22:05 被阅读504次

    父子组件的生命周期顺序

    父组件app.vue

    <template>
      <div id="app">
        <hello></hello>
      </div>
    </template>
    <script>
    import Hello from './components/Hello'
    export default {
      name: 'app',
      components: {
        Hello
      },
      beforeCreate() {
        console.log('I am parents beforeCreated');
      },
      created() {
        console.log('I am parents created');
      },
      beforeMount() {
        console.log('I am parents beforeMount');
      },
      mounted() {
        console.log('I am parents mounted');
      }
    }
    </script>
    

    子组件hello.vue

    <template>
      <div class="hello">
        hello
      </div>
    </template>
    <script>
    export default {
      name: 'hello',
     beforeCreate() {
        console.log('I am child beforeCreated');
      },
      created() {
        console.log('I am child created');
      },
      beforeMount() {
        console.log('I am child beforeMount');
      },
      mounted() {
        console.log('I am child mounted');
      }
     }
    </script>
    

    执行的结果:

    I am parents beforeCreated
    I am parents created
    I am parents beforeMount
    I am child beforeCreated
    I am child created
    I am child beforeMount
    I am child mounted
    I am parents mounted
    

    结论:父子组件的执行顺序为,
    父组件beforeCreated ->父组件created ->父组件beforeMounted ->子组件beforeCreated ->子组件created ->子组件beforeMounted ->子组件mounted -> 父组件mounted。

    继承组件的生命周期

    base.vue

    <template>
      <div>
        base
      </div>
    </template>
    <script>
      export default {
     beforeCreate() {
          console.log('I am base beforeCreated');
        },
        created() {
          console.log('I am base created');
        },
        beforeMount() {
          console.log('I am base beforeMount');
        },
        mounted() {
          console.log('I am base mounted');
        }
      }
    </script>
    

    hello.vue

    <template>
      <div class="hello">
        hello
      </div>
    </template>
    <script>
    import Base from './base.vue'
    export default {
      extends: Base,
      beforeCreate() {
        console.log('I am beforeCreated');
      },
      created() {
        console.log('I am created');
      },
      beforeMount() {
        console.log('I am beforeMount');
      },
      mounted() {
        console.log('I am mounted');
      }
    }
    </script>
    

    执行结果:

    I am base beforeCreated
    I am beforeCreated
    I am base created
    I am created
    I am base beforeMount
    I am beforeMount
    I am base mounted
    I am mounted
    

    结论:继承组件生命周期是交替执行的

    相关文章

      网友评论

      • 一蓑烟雨任平生_cui:你好,为什么是子组件的mounted先于父组件执行?
        5df463a52098:@一萧烟雨任平生 mounted是页面初始化后执行,子组件渲染完成后父组件才能渲染完成,子组件的mounted必然先于父组件

      本文标题:vue父子组件&继承组件的生命周期

      本文链接:https://www.haomeiwen.com/subject/wqpjkftx.html