Vue父子组件生命周期触发顺序以及mixin

707 阅读1分钟

1 - 例子

①父组件 - parent.vue

<template>
  <div>
    父组件
    <Child />
  </div>
</template>

<script>
import Child from './child'
import mixin from './mixin.js'
export default {
  components: {
    Child
  },
  mixins: [mixin],
  beforeCreate() {
    console.info('父 beforeCreate')
  },
  created() {
    console.info('父 created')
  },
  beforeMount() {
    console.info('父 beforeMount')
  },
  mounted() {
    console.info('父 mounted')
  }
}
</script>

②子组件 - Child

<template>
  <div>
    子组件
  </div>
</template>

<script>
export default {
  beforeCreate() {
    console.info('子 beforeCreate')
  },
  created() {
    console.info('子 created')
  },
  beforeMount() {
    console.info('子 beforeMount')
  },
  mounted() {
    console.info('子 mounted')
  }
}
</script>

③mixin - mixin.js

export default {
  beforeCreate() {
    console.info('mixin - beforeCreate')
  },
  created() {
    console.info('mixin - created')
  },
  beforeMount() {
    console.info('mixin - beforeMount')
  },
  mounted() {
    console.info('mixin - mounted')
  }
}

控制台打印结果:

微信图片_20210520160144.png

总结

首次加载生命周期触发顺序
mixin的beforeCreate > 父beforeCreate > mixin的created > 父created > mixin的beforeMount > 父beforeMount > 子beforeCreate > 子created > 子beforeMount > 子mounted > mixin的mounted >父mounted
更新
父beforeUpdate > 子beforeUpdate > 子updated > 父updated
销毁
父beforeDestroy > 子beforeDestroy > 子destroyed > 父destroyed

2 - mixin冲突处理

1、由上面例子可知,mixin生命周期不会和组件生命周期冲突,且会在组件对应的生命周期之前触发mixin生命周期

2、当组件选项与mixin混入选项冲突时(重名)以组件优先

const mixin = {
  data() {
    return {
      msg: 'Msg - mixin'
    }
  },
  methods: {
    foo() {
      console.log('foo - mixin')
    }
  }
}

export default {
  mixins: [mixin],
  data() {
    return {
      msg: 'Msg'
    }
  },
  mounted() {
    this.foo() // foo
    console.info(this.msg) // Msg
  },
  methods: {
    foo() {
      console.info('foo')
    }
  }
}