Vue生命周期
下图展示了实例的生命周期。你不需要立马弄明白所有的东西,不过随着你的不断学习和使用,它的参考价值会越来越高。
<div id="app">
<h1>{{ msg }}</h1>
</div>
var app = new Vue({
el: "#app",
data: {
msg: "helloVue",
className: "redBg"
},
beforeCreate(){
console.log("beforeCreate");
// 此时数据data和事件方法methods还未绑定到app对象上
// console.log(this);
// console.log(this.msg);
// console.log(this.clickEvent);
},
created(){
console.log("created");
// 数据data和方法methods绑定到应用对象app上
// console.log(this);
// console.log(this.msg);
// console.log(this.clickEvent);
},
beforeMount(){
console.log("beforeMount");
// 渲染之前,根据数据生成的DOM对象是获取不到的
let dom = document.querySelector(".redBg");
console.log(dom);
},
mounted(){
console.log("mounted");
// 渲染之后,可以获取数据生成的DOM对象
let dom = document.querySelector(".redBg");
console.log(dom);
},
methods: {
clickEvent: function(){
}
},
beforeUpdate() {
// 数据更改,但内容未更改之前
console.log("beforeUpdate");
let dom = document.querySelector(".redBg");
console.log(dom);
},
updated() {
// 内容已更新完毕
console.log("update");
let dom = document.querySelector(".redBg");
console.log(dom);
},
beforeDestroy() {
},
destroyed() {
}
})
在刷新页面后,依次触发四个事件:
-
beforeCreate事件
Vue {_uid: 0, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
undefinedundefined
说明在beforeCreate事件触发时,Vue刚刚实例化,而此时数据data和事件方法methods还未绑定到app对象上。
-
created事件
Vue {_uid: 0, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
helloVue
ƒ (){}说明在create事件触发时,数据data和方法methods绑定到应用对象app上。
-
beforeMount事件
null
在渲染页面之前,数据是没有挂载的,根据数据生成的DOM对象是获取不到的
-
mount事件
<h1 class="redBg">helloVue</h1>
在渲染页面之后,数据是已经挂载的,可以获取数据生成的DOM对象
在修改数据之后,依次再触发两个事件:
-
beforeUpdate事件
<h1 class="redBg">123</h1>
我这里是在修改数据之前能获取到数据
-
update事件
<h1 class="redBg">123</h1>
在修改数据之后也能获取到数据
在数据销毁之后,依次再触发两个事件:
- beforeDestory事件
- destoryed事件
想要看到销毁事件触发的效果需要先事先写好一个自定义组件
这个
<hello-com></hello-com>
就是自定义组件然后当销毁这个自定义组件的时候就会触发这两个销毁事件
<div id="app">
<hello-com v-if="isShow"></hello-com>
</div>
var helloCom = Vue.component("hello-com",{
template: "<div><h1>{{ maxiaoyu }}</h1><button @click='changeData'>修改数据</button></div>",
data: function(){
return {
maxiaoyu: "hello maxiaoyu"
}
},
methods: {
changeData: function(){
this.maxiaoyu = "hello 小明"
}
},
beforeCreate(){
console.log("beforeCreate");
// 此时数据data和事件方法methods还未绑定到app对象上
},
created(){
console.log("created");
// 数据data和方法methods绑定到应用对象app上
},
beforeMount(){
console.log("beforeMount");
// 渲染之前,根据数据生成的DOM对象是获取不到的
},
mounted(){
console.log("mounted");
// 渲染之后,可以获取数据生成的DOM对象
},
beforeUpdate() {
// 数据更改,但内容未更改之前
console.log("beforeUpdate");
},
updated() {
// 内容已更新完毕
console.log("update");
},
beforeDestroy() {
// 应用销毁之前
console.log("beforeDestroy");
},
destroyed() {
// 应用销毁之后
console.log("destroyed");
}
})
var app = new Vue({
el: "#app",
data: {
isShow: true
},
components: {
"hello-com": helloCom
}
})
提示:可以在控制台输入 app.isShow = false 来销毁这个自定义组件
只有v-if 可以销毁,v-show 不能销毁,v-show 只是修改了组件的属性值为display: none