vue.js基础__Vue的生命周期(钩子函数)

Vue的生命周期,也就是钩子函数;Vue一共有10个生命周期函数,

我们可以利用这些函数在vue的每个阶段都进行操作数据或者改变内容

代码示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue的生命周期</title>
<script src="../assets/js/vue.js"></script>
</head>

<body>
<h1>Vue的生命周期</h1>
<hr>
<div id="app">
{{count}}
<p><button @click="add">add</button></p>
</div>
<button onclick="app.$destroy()">destroy</button>

<script>
var app = new Vue({
el: '#app',
data: {
count: 1
},
methods: {
add: function () {
this.count++
}
},
beforeCreate() {
console.log('1 - beforeCreate 初始化之后')
},
created() {
console.log('2 - created 创建完成')
},
beforeMount() {
console.log('3 - beforeMount 挂载之前')
},
mounted() {
console.log('4 - mounted 被挂载之后')
},
beforeUpdate() {
console.log('5 - beforeUpdate 数据更新前')
},
updated() {
console.log('6 - updated 被更新后')
},
activated() {
console.log('7 - activated')
},
deactivated() {
console.log('8 - deactivated')
},
beforeDestroy() {
console.log('9 - beforeDestroy 销毁之前')
},
destroyed() {
console.log('10 - destroyed 销毁之后')
},
})
</script>
</body>

</html>

运行以上代码可以看出,1,2,3,4首先进行加载,点击后5,6加载,当点击销毁时,9,10进行加载;

在vue 中生命周期函数,也就是钩子函数,还是非常常用的,因为是单页面应用,

所以需要加载大量资源和图片

原文地址:https://www.cnblogs.com/sunyang-001/p/11100008.html