Vue的生命周期
1.图解
2.概述
Vue实例的生命周期主要有8个钩子函数,分别为beforeCreate、 created、 beforeMount、mounted、 beforeUpdate、 updated、beforeDestroy、 destroyed
详解:
beforeCreate:数据data和事件方法methods还未绑定到对象上
created: 数据data和方法methods绑定到应用对象上
beforeMount: 渲染之前,根据数据生成的DOM对象是获取不到的
mounted: 渲染之后,可以获取数据生成的Dom对象
beforeUpdate: 数据更改,但内容未更改之前
updated: 内容已更新完毕
beforeDestroy: 应用销毁之前
destroyed:应用销毁之后
3.实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/vue.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<h1>{{msg}}</h1>
<h1 :class="className">类名绑定</h1>
<!-- v-if和v-show运用时在销毁时的体现-->
<hello-com v-if="isShow"></hello-com>
<hello-com v-show="isShow"></hello-com>
</div>
<script type="text/javascript">
// 创建一个组件来试验销毁功能
let helloCom = Vue.component("hello-com", {
template: '<div><h1>{{xiaomin}}</h1><button @click="dataChange">修改数据</button></div>',
data: function () {
return {
xiaomin: "hello xiaomin"
}
},
methods: {
dataChange: function () {
this.xiaomin = "hello 微滑低"
}
},
var app = new Vue({
el: "#app",
data: {
msg: "hello vue",
className: "red",
isShow: true,
},
beforeCreate() {
// 此时数据data和事件方法methods还未绑定到app对象上
console.log('beforeCreate')
},
created() {
// 数据data和方法methods绑定到应用对象app上
console.log('created')
console.log(this),
console.log(this.msg),
console.log(this.clickEvent)
},
beforeMount() {
// 渲染之前,根据数据生成的DOM对象是获取不到的
console.log('beforeMount')
let dom = document.querySelector(".red")
console.log(dom)
},
mounted() {
// 渲染之后,可以获取数据生成的Dom对象
console.log('mounted')
let dom = document.querySelector(".red")
console.log(dom)
},
beforeUpdate() {
// 数据更改,但内容未更改之前
console.log('beforeUpdate')
},
updated() {
// 内容已更新完毕
console.log('updated')
},
beforeDestroy() {
// 应用销毁之前
console.log('beforedestroy')
},
destroyed() {
// 应用销毁之后
console.log('destroyed')
},
methods: {
clickEvent: function () {
}
}
})
</script>
</body>
</html>