首先,每个Vue实例在被创建之前都要经过一系列的初始化过程,这个过程就是vue的生命周期。首先看一张官方图片:
可以看到在vue一整个的生命周期中会有很多钩子函数提供给我们在vue生命周期不同的时刻进行操作, 那么先列出所有的钩子函数,然后我们再一一详解:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- activated
- deactivated
- beforeDestroy
- destroyed
来波代码,复制在浏览器中运行,打开console查看就行了:
<script>
var Vcontent = {
template: `
<div>
<span>{{msg}}</span>
<button @click="changeDate">改变</button>
</div>
`,
data() {
return {
msg: 'helloword'
}
},
methods: {
changeDate() {
this.msg = this.msg + '哈哈哈'
}
},
beforeCreate:function() {
// 组件创建之前
console.log(this.msg,'===============');
},
created:function() {
// 组件创建之后
// 使用该组件,就会调用created方法 在created这个方法中可以操作后端的数据,数据响应视图
// 应用: 发起ajax请求
console.log(this.msg,'++++++++++++');
this.msg = '改变了吧'
},
beforeMount:function () {
// 挂载数据到DOM之前会调用
console.log(document.getElementById('app'),'---------------');
},
//从这个方法开始: 我们操作的都是虚拟 dom 更新数据时候;都是有 vue操作DOM
// 证明了; vue 是数据驱动视图
mounted:function() {
// 挂载数据到DOM之后会调用 Vue 作用以后的DOM
console.log(document.getElementById('app'),'???????????????');
},
beforeUpdate(){
// 在更新DOM之前 调用此钩子函数 应用:可以获取原始的DOM
console.log(document.getElementById('app').innerHTML,'>>>>>>>>>>>>>>');
console.log('数据更新之前')
},
updated(){
// 在更新DOM之后 调用此钩子函数 应用:可以获取最新的DOM
// console.log(document.getElementById('app').innerHTML,'<<<<<<<<<<<<<<');
console.log('数据更新之后')
},
beforeDestroy(){
// 组件销毁之前
console.log('beforeDestroy');
},
destroyed(){
// 组件销毁之后
console.log('destroyed');
},
activated(){
console.log('组件被激活了');
},
deactivated(){
console.log('组件被停用了');
}
}
// Vue的内置组件,能在组件的切换过程中将状态保留在内存中父,防止重复渲染DOM
var App = {
template: `
<div>
<keep-alive>
<Vcontent v-if='isShow'></Vcontent>
</keep-alive>
<button @click='changeDom'>改变生死</button>
</div>
`,
data() {
return {
isShow: true,
}
},
components: {
Vcontent,
},
methods:{
changeDom(){
this.isShow = !this.isShow
}
}
}
new Vue({
el: "#app",
template: `<App></App>`,
components: {
App,
}
})
</script>
总结
我们可以使用生命周期钩子在Vue对象生命周期的不同阶段添加我们的自定义代码。它将帮助我们控制在DOM中创建对象时创建的流程,以及更新和删除对象。