vue生命周期

1.Vue1.0生命周期

1.1钩子函数:

created ->   实例已经创建
beforeCompile ->   编译之前
compiled ->   编译之后
ready ->   插入到文档中

beforeDestroy ->   销毁之前
destroyed ->   销毁之后

1.2生命周期图示


下图说明了实例的生命周期。你不需要立马弄明白所有的东西,不过以后它会有帮助。

1.3代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/vue.js"></script>
<script src="../js/vue-resource.js"></script>
</head>
<body>
<div id="box">
{{message}}
</div>
<script>
var vm = new Vue({
el:"#box",
data:{
message:"张三"
},
/**
* 修改默认初始化的数据
*/
created:function(){
this.message = "created";
},

/**
* 编译模板
*/
beforeCompile:function () {
this.message = "beforeCompile";
},
compiled:function () {
this.message = "compiled";
},

/**
* 将编译好的模板通过ready渲染到DOM,在渲染到DOM之前我们可以在ready函数中增加一些自己的业务逻辑
*/
ready:function(){
this.message = "ready"
},

/**
* 将内存中的数据销毁
*/
beforeDestroy:function () {
//销毁的目的是干掉内存中数据,并不是修改内存中数据所以这里没有用this.message=""这样做是有问题不合理的
alert('beforeDestroy');
},
destroyed:function () {
//销毁的目的是干掉内存中数据,并不是修改内存中数据所以这里没有用this.message=""这样做是有问题不合理的
alert('destroyed');
}
});

document.onclick = function () {
vm.$destroy();
}
</script>
</body>
</html>
 

2.Vue2.0生命周期

2.1钩子函数

beforeCreate 组件实例刚刚被创建,属性都没有
created 实例已经创建完成,属性已经绑定
beforeMount 模板编译之前
mounted 模板编译之后,代替之前ready  *
beforeUpdate 组件更新之前
updated 组件更新完毕 *
beforeDestroy 组件销毁前
destroyed 组件销毁后

2.2示例图

总体分为4步骤:实例创建前后,模板编译前后,组件更新前后,组件销毁前后

 

2.3代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue2.0声明周期</title>
<script src="./../bower_components/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<strong v-text="message"></strong>
<button type="button" @click="update">更新</button>
<button type="button" @click="destroy">卸载</button>
</div>
<script>
new Vue({
data(){
return {
message:"更新前"
}
},
methods:{
update(){
this.message = "我被更新了"
},
destroy(){
this.$destroy();
}
},
//data数据初始化前,组件实例刚刚被创建,属性都没有
beforeCreate(){
alert('数据初始化中...,当前message='+this.message);
},
//实例已经创建完成,属性已经绑定
created(){
alert("实例创建完毕,当前message="+this.message);
},
//实例挂在到DOM前
beforeMount(){
alert("实例数据将要挂在到DOM上");
},
//实例数据已经挂在到DOM上
mounted(){
alert("实例数据已经挂在到DOM上");
},

//更新组件前
beforeUpdate(){
alert("更新组件前message="+this.message);
},

//更新组件后
updated(){
alert("组件更新完毕message="+this.message);
},

beforeDestroy(){
alert("组件销毁前");
},
destroyed(){
alert("组件销毁后");
}
}).$mount("#app")
</script>
</body>
</html>






 




posted on 2016-12-24 11:10  虫虫爬啊爬  阅读(619)  评论(0编辑  收藏  举报

导航