//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../8-20/js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="out">
<h1>{{tit}}</h1>
<button @click="tap1()">更新</button>
<button @click="tap()">销毁</button>
</div>
</body>
<script type="text/javascript">
var vm = new Vue({
el:"#out",
data:{
tit:"hello"
},
methods:{
tap1(){
this.tit="hello world"
},
tap(){
this.$destroy()
}
},
beforeCreate(){
//console.log(this.tit) //undefined
//console.log(this.$el) //undefined
},
created(){
console.log(this.tit) //hello
console.log(this.$el) //undefined
},
beforeMount(){
console.log(this.tit) //hello
console.log(this.$el) //<div id="out"><h1>{{tit}}</h1></div>
},
mounted(){
console.log(this.tit) //hello
console.log(this.$el) //<div id="out"><h1>hello</h1></div>
},
beforeUpdate(){
console.log("更新之前") //点击更新按钮,触发
},
updated(){
console.log("更新之后----") //点击更新按钮,触发
},
beforeDestroy(){
console.log("实例销毁之前") //点击销毁按钮触发,但是视图并未更新过来
},
destroyed(){
console.log("实例销毁之后") //销毁只是vue实例和其他东西解绑,视图并不会被销毁
}
})
</script>
</html>
生命周期钩子函数中最常用的是beforeCreate和mounted两个,beforeCreate可以用于在视图加载之前展示一个loading页面。二mounted可以发起ajax请求。下面在beforeCreate钩子函数里面写入一个加载的插件,代码如下:
//稍微修改上面代码
//引入文件
<link rel="stylesheet" type="text/css" href="../js/css/animate.css"/>
<link rel="stylesheet" type="text/css" href="../js/css/global.css"/>
<link rel="stylesheet" type="text/css" href="../js/css/loading.css"/>
<script src="../8-20/js/jquery-1.10.1.js" type="text/javascript" charset="utf-8"></script>
<script src="../8-20/js/vue.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/loading.js" type="text/javascript" charset="utf-8"></script>
//其他部分更改
<script type="text/javascript">
beforeCreate(){
//console.log(this.tit) //undefined
//console.log(this.$el) //undefined
//加载loading插件
$('body').loading({
loadingWidth:240,
title:'请稍等!',
name:'test',
discription:'描述描述描述描述',
direction:'column',
type:'origin',
// originBg:'#71EA71',
originDivWidth:40,
originDivHeight:40,
originWidth:6,
originHeight:6,
smallLoading:false,
loadingMaskBg:'rgba(0,0,0,0.2)'
});
},
//......
mounted(){
console.log(this.tit) //hello
console.log(this.$el) //<div id="out"><h1>hello</h1></div>
//移除loading
setTimeout(function(){
removeLoading('test');
},3000);
}
</script>
钩子函数:一方面有变动,另一方面立马来处理变动的函数,成为钩子函数(说白了就是管理组件变化的函数)。
This指向必须指向实例化本身。所有的生命周期钩子自动绑定this上下文到实例中,因此你可以访问数据,对属性和方法进行运算。所以不能使用箭头函数来定义一个生命周期方法(例如:created: () => this.fetchTodos()),箭头函数绑定了父上下文,this并不指向Vue实例,this.fetchTodos 的行为未定义。
四个阶段:创建、挂载、更新、销毁
注:钩子函数官方API上给有十一个,但是常见的就上面提到的八个
beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,activated,deactivated,beforeDestroy,destroyed,errorCaptured