在 Vue 实例中,书写vue生命周期
import Vue from 'vue'
import App from './App'
import router from './router'
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
beforeCreate () {
console.log('beforeCreate')
},
created () {
console.log('created')
},
beforeMount () {
console.log('beforeMount')
},
mounted() {
console.log('mounted')
},
beforeUpdate () {
console.log('beforeUpdate')
},
updated () {
console.log('updated')
},
beforeDestory () {
console.log('beforeDestory')
},
destoryed () {
console.log('destoryed')
}
})
注意:
(1)beforeMount 和 mounted 是依赖挂载元素 el 的,如果el 没有值,或者没有定义 el,就不会触发这两个生命周期,因为不知道挂载到哪里去,比如将el 这行注释掉,运行结果
beforeMount 和 mounted 同时也会监听挂载,如果挂载完成会立即执行beforeMount 和 mounted
import Vue from 'vue'
import App from './App'
import router from './router'
const app = new Vue({
// el: '#app',
router,
components: { App },
template: '<App/>',
beforeCreate () {
console.log('beforeCreate', this.$el)
},
created () {
console.log('created', this.$el)
},
beforeMount () {
console.log('beforeMount', this.$el)
},
mounted() {
console.log('mounted', this.$el)
}
})
setTimeout(() => {
app.$mount('#app')
}, 2000)
2s之后挂载,则 beforeMount 和 mounted 会 2s 后等挂载完成后执行
(2)beforeUpdate 和 updated:当数据更新的时候会触发
(3)挂载时期
beforeCreate () {
console.log('beforeCreate', this.$el)
},
created () {
console.log('created', this.$el)
},
beforeMount () {
console.log('beforeMount', this.$el)
},
mounted() {
console.log('mounted', this.$el)
},
可以看到 beforeCreate 和 created 还没挂载,所以在这两个生命周期中获取DOM是不能获取的
(4)render 函数 执行是在 beforeMount 和 Mounted 之间
import Vue from 'vue'
import App from './App'
import router from './router'
const app = new Vue({
// el: '#app',
router,
components: { App },
// template: '<App/>',
beforeCreate () {
console.log('beforeCreate', this.$el)
},
created () {
console.log('created', this.$el)
},
beforeMount () {
console.log('beforeMount', this.$el)
},
mounted() {
console.log('mounted', this.$el)
},
// render 函数
render (h) {
console.log('render')
return h('div', {}, 'hihi')
}
})
setTimeout(() => {
app.$mount('#app')
}, 2000)
2s 之后挂载完成,执行 beforeMount ,执行 render,执行 mounted