技术文章

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

2018-04-15  本文已影响504人  5df463a52098

父子组件的生命周期顺序

父组件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

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

上一篇下一篇

猜你喜欢

热点阅读