目录1. 生命周期(重要)1.1 初步认识生命周期1.2 生命周期流程(8个)1.3 生命周期详细流程图1.4 常用的生命周期钩子:1.4.1 关于销毁1.4.2 关于父子组件的生命
1.初始化
1.beforeCreate()
2.created()
2.挂载(页面渲染)
1.beforeMount()
2.mounted()
3.更新
1.beforeUpdate()
2.updated()
4.销毁
1.beforeDestory()
2.destoryed()
beforeCreate()
:可以配置全局事件总线,后面会讲到先提一嘴
mounted()
: 可以在此阶段发送ajax请求, 启动定时器、绑定自定义事件、订阅消息等异步任务【初始化操作】
beforeDestroy()
: 在此阶段做收尾工作, 如: 清除定时器、解绑自定义事件、取消订阅消息等【首尾工作】
1.加载渲染的过程
父beforeCreate ==> 父created ==> 父beforeMount ==> 子beforeCreate ==> 子created ==> 子beforeMount ==> 子mounted ==> 父mounted
2.更新的过程
父beforeUpdate ==> 子beforeUpdate ==> 子updated ==> 父updated
3.销毁过程
父beforeDestroy ==> 子beforeDestroy ==> 子destroyed ==> 父destroyed
<div id="root">
<!-- 让h3透明度产生过渡的效果 -->
<h3 :style="{opacity:opacity}">欢迎学习Vue!</h3>
<button @click="des">点击我销毁</button>
</div>
<script>
Vue.config.productionTip = false
let vm = new Vue({
el: '#root',
data: {
opacity: 1
},
methods: {
des(){
// 触发此函数必定调用,beforeDestroy(),destroyed()
this.$destroy()
}
},
mounted() { //挂载
this.timer = setInterval(() => {
this.opacity -= 0.01
if (this.opacity <= 0)
this.opacity = 1
}, 10);
},
beforeDestroy() {
console.log("beforeDestroy - 清除定时器");
clearInterval(this.timer)
},
destroyed() {
console.log("destroyed - 销毁完毕")
},
})
</script>
<div id="root">
<h3>n的值为:{{n}}</h3>
<button @click="add">点击我n+1</button>
<button @click="remove">点击销毁vm</button>
</div>
<script>
Vue.config.productionTip = false
let vm = new Vue({
el: '#root',
data: {
n:1
},
methods: {
add(){
this.n++
},
remove(){
this.$destroy()
}
},
beforeCreate() {
console.log("beforeCreate");
//console.log(this.n); //undefined
// console.log(this.add()); // this.add is not a function
// debugger
},
created() {
console.log("created");
// console.log(this.n); // 1
// console.log(this.add()); // undefined
// debugger
},
beforeMount() {
console.log("beforeMount");
// debugger
},
mounted() {
console.log("mounted");
// debugger
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeDestroy() {
console.log("beforeDestroy");
},
destroyed() {
console.log("destroyed");
},
})
</script>
以上就是今天要讲的内容,本文介绍了生命周期的相关知识,希望对大家有所帮助!
--结束END--
本文标题: Vue的生命周期一起来看看
本文链接: https://www.lsjlt.com/news/140434.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0