Vue.js开发实践(10)-Vue实例的生命周期及钩子函数
更多关于Vue.js的系列文章请点击:Vue.js开发实践(0)-目录页
一、什么是Vue的生命周期和钩子函数
每一个Vue实例被创建出来、属性和选项渲染、el实例挂载再到其销毁过程被称为一个Vue实例的生命周期,在这一系列过程中,我们可以使用Vue的生命周期钩子函数在特定的时间对Vue实例进行一系列的操作。
以下是一个关于Vue实例生命周期的详解图:
二、生命周期钩子函数的简单使用
关于各生命周期钩子函数的作用时刻:使用的形式如下:
new Vue({
el: '#home',
mounted:function(){
//...
}
})
或者
mounted(){
//...
}
需要注意的是,mounted 钩子函数不会承诺所有的子组件也都一起被挂载。如果希望等到整个视图都渲染完毕,可以用 vm.$nextTick 替换掉 mounted:
new Vue({
el: '#home',
mounted:function(){
this.$nextTick(function(){
//...
})
}
})
以下是一个简单的使用例子:
- HelloWorld.vue
<template>
<div id="hello">
<h1>{{message}}</h1>
</div>
</template>
<script>
export default {
data () {
return {
message: 'Welcome to Your Vue.js App'
}
},
mounted(){
//挂载实例完成后
console.log("实例挂载完成钩子");
},
created(){
console.log("实例创建完成钩子");
this.showMessage();
},
methods: {
showMessage(){
console.log("实例创建完成之后才调用的方法");
}
}
}
</script>
- index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>hellovue</title>
</head>
<body>
<div id="home">
<hello-world></hello-world>
</div>
</body>
</html>
- main,js
import HelloWorld from '@/components/HelloWorld.vue'
Vue.config.productionTip = false
new Vue({
el: '#home',
components: {
HelloWorld
}
})