可以总共分为8个阶段:
beforeCreate(创建前)
created(创建后)
beforeMount(载入前)
mounted(载入后)
beforeUpdate(更新前)
updated(更新后)
activated/deactivated
(keep-alive 组件激活时调用/keep-alive 组件停用时调用)beforeDestroy(销毁前,不能和keep-alive 在一起使用)
destroyed(销毁后,不能和keep-alive 在一起使用)
使用场景
1、Vue-cli 中为单独页面设置背景色
只需要给单独页面添加如下js
created (){
document.body.style.background='#ededed';
},
beforeDestroy(){
document.body.style.background='#f5f5f5';
},
2、demo
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script src="../js/vue.js"></script>
<title></title>
</head>
<body>
<div id='app'>
{{a}}
<button v-on:click="change">change</button>
</div>
<script>
var myVue = new Vue({
el: "#app",
data: {
a: "Vue.js1"
},
methods:{
change:function(){
this.a='Vue.js2'
}
},
beforeCreate: function() {
console.log("创建前")
console.log(this.a)
console.log(this.$el)
},
created: function() {
console.log("创建之后");
console.log(this.a)
console.log(this.$el)
},
beforeMount: function() {
console.log("mount之前")
console.log(this.a)
console.log(this.$el)
},
mounted: function() {
console.log("mount之后")
console.log(this.a)
console.log(this.$el)
},
beforeUpdate: function() {
console.log("更新前");
console.log(this.a)
console.log(this.$el)
},
updated: function() {
console.log("更新完成");
console.log(this.a);
console.log(this.$el)
},
beforeDestroy: function() {
console.log("销毁前");
console.log(this.a)
console.log(this.$el)
console.log(this.$el)
},
destroyed: function() {
console.log("已销毁");
console.log(this.a)
console.log(this.$el)
}
})
</script>
</body>
</html>
生成效果图
QQ截图20171206182310.png
网友评论