6.Vue生命周期
6.1 生命周期
6.1.1 生命周期图示
从图中可以看出,一个组件从被创建到最后被销毁,总共要经历8个过程:
- beforeCreate:实例创建前
- created:实例创建完毕
- beforeMount:DOM挂载前
- mounted:DOM挂载完毕
- beforeUpdate:数据更新前
- unpdated:数据更新完毕
- beforeUnmount:解除DOM挂载前
- unmounted:解除DOM挂载完毕
6.1.2 代码演示
<body>
<div id="app">
<mycomponent v-if="isShow"></mycomponent>
<button @click="change">{{ msg }}</button>
</div>
<script src="../js/vue3.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
isShow: true,
msg: '隐藏'
}
},
methods: {
change() {
this.isShow = !this.isShow
this.msg = this.isShow ? '隐藏' : '显示'
}
}
})
app.component('mycomponent', {
template: `<div>
{{ num }} <button @click="add">加</button>
</div>`,
data() {
return {
num: 0
}
},
methods: {
add() {
this.num++
}
},
beforeCreate() {
console.log('beforeCreate - Vue实例创建前的生命周期函数')
},
created() {
console.log('created - Vue实例创建后的生命周期函数')
},
beforeMount() {
console.log('beforeMount - Vue实例挂载DOM前的生命周期函数')
},
mounted() {
console.log('mounted - Vue实例挂载DOM后的生命周期函数')
},
beforeUpdate() {
console.log('beforeUpdate - 数据更新前的生命周期函数')
},
updated() {
console.log('updated - 数据更新后的生命周期函数')
},
beforeUnmount() {
console.log('beforeUnmount - Vue实例卸载前的生命周期函数')
},
unmounted() {
console.log('unmounted - Vue实例卸载后的生命周期函数')
}
})
app.mount('#app')
</script>
</body>
6.2 在Vue中操作DOM
<body>
<div id="app">
<mycomponent v-if="isShow"></mycomponent>
<button @click="change">{{ msg }}</button>
</div>
<script src="../js/vue3.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
isShow: true,
msg: '隐藏'
}
},
methods: {
change() {
this.isShow = !this.isShow
this.msg = this.isShow ? '隐藏' : '显示'
}
}
})
app.component('mycomponent', {
template: `<div>
{{ num }} <button @click="add" ref="btn">加</button>
</div>`,
// ref="btn" 引用,用于获取按钮元素
data() {
return {
num: 0
}
},
methods: {
add() {
this.num++
}
},
beforeCreate() {
console.log('beforeCreate - Vue实例创建前的生命周期函数')
},
created() {
console.log('created - Vue实例创建后的生命周期函数')
},
beforeMount() {
console.log('beforeMount - Vue实例挂载DOM前的生命周期函数')
},
mounted() {
let domObj = this.$refs.btn
// console.log(domObj)
domObj.style.color = 'skyblue'
console.log('mounted - Vue实例挂载DOM后的生命周期函数')
},
beforeUpdate() {
console.log('beforeUpdate - 数据更新前的生命周期函数')
},
updated() {
console.log('updated - 数据更新后的生命周期函数')
},
beforeUnmount() {
console.log('beforeUnmount - Vue实例卸载前的生命周期函数')
},
unmounted() {
console.log('unmounted - Vue实例卸载后的生命周期函数')
}
})
app.mount('#app')
</script>
</body>
标签:学习,Vue,console,log,DOM,周期函数,---,实例,Vue3
From: https://www.cnblogs.com/yishengwanwuzhao/p/18363752