备注:vue.3.0的生命周期与渲染等机制有变化,这里仅是适用vue2.0
一、vue2.0生命周期
beforeCreate(创建前)、created(创建后)
beforeMount(载入前)、mounted(载入后)
beforeUpdate(更新前)、updated(更新后)
beforeDestroy(销毁前)、destroyed(销毁后)
二、问题:
1.vue第一次页面加载会触发四个钩子函数 ?
beforeCreate、created、beforeMount、mounted。(创建前后,挂载前后)
2.DOM渲染在哪发生?
在mounted(载入后)这个周期中就已经完成。
3.更新渲染如何操作?
this.$forceUpdate(); 进行强制刷新
解决方法:使用Vue.set(target,key,value)。
target:要更改的数据源(可以是对象或者数组),
key:要更改的具体数据,
value :重新赋的值。
this.$set(this.currentData,'bound',this.value);
当生成Vue实例后,当再次给数据赋值时,有时候并不会自动更新到视图上去,这里使用set更好。
4.子组件的强制刷新:
1.route强制刷新(不建议)
this.$router.go(0);
window.location.reload();
2.使用v-if (比较常见,直接操作子组件)
3.provide和inject(控制route-view的生成与销毁,达到更新作用)
父组件:
<template>
<div id="app">
<keep-alive>
<router-view v-if="isRouterAlive"></router-view>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App',
provide () { // 在祖先组件中通过 provide 提供变量
return {
reload: this.reload // 声明一个变量
}
},
data () {
return {
isRouterAlive: true // 控制 router-view 是否显示达到刷新效果
}
},
methods: {
// provide中声明的变量
reload () {
// 通过 this.isRouterAlive 控制 router-view 达到刷新效果
this.isRouterAlive = false
this.$nextTick(function () {
this.isRouterAlive = true
})
}
}
}
</script>
子组件:
<template>
<div class="page">
<button @click="reloadFun">刷新</button>
</div>
</template>
<script>
import Vue from 'vue';
export default {
inject:['reload'], // 使用 inject 注入 reload 变量
data(){
return{
}
},
methods: {
reloadFun(){
this.reload(); // 直接使用
}
},
mounted() {}
}
</script>
4.使用key-changing优化组件(最好方式)
对性能渲染要求不高,实现无缝更新子组件。优先使用
注意:用key时,一定要保证子组件有mounted或者created并且在他俩中做初始化,不然用Key就没有意义了。
<template>
<div :key="key">内容</div>
<el-button @click="refresh()">操作</el-button>
</template>
<script>
export default {
data() {
return {
key: 0
}
},
methods: {
refresh() {
this.key++;
}
}
}
</script>
并且改变props的值要在key更新和showModal=true之前(其实如果props的值是不用调接口的并且是同步的情况下,可以写在key更新之后,但是为了代码规范和较少问题,还是写在前面比较好!)。但是如果子组件里有监听showModal,那也可以写在key更新之后,通过监听来触发子组件方法。(目前我都是在子组件mounted里执行)。
三、借用杨肆月对于Vue生命周期的图解,进行解析机制变化。
常用的生命周期钩子:
1.created: 初始赋值结束,在这结束loading,还做一些初始化,实现函数自执行,created中赋值不会触发更新生命周期。
2.mounted: 发送ajax请求、启动定时器、绑定自定义事件等。
3.beforeDestroy: 清除定时器、解绑自定义事件、释放内存等。
关于销毁Vue实例
1.销毁后借助Vue开发者工具看不到任何信息。
2.销毁后自定义事件会失效,但原生DOM事件依然有效。
3.一般不会再beforeDestroy操作数据。因为即便操作数据。也不会再触发更新流程了-
created和mounted有什么区别?
created不能获取dom节点,mounted能获取到dom节点
什么时候用created、mounted?
如果不需要对dom进行操作用created,反之用mounted;并且mounted中的数据更新会引起更新生命周期,created不会引起更新生命周期
四、父子组件生命周期顺序:
子组件更新过程:
父beforeUpdate > 子beforeUpdate > 子updated > 父updated
父组件更新过程:
影响到子组件: 父beforeUpdate > 子beforeUpdate > 子updated > 父updated
不影响子组件: 父beforeUpdate > 父updated
销毁过程:
父beforeDestroy > 子beforeDestroy > 子destroyed > 父destroyed