<!DOCTYPE html>
<html>
<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">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<label>生日</label>
<input type="date" v-model="birthday"/>
<div>當前用戶{{getAge}}週歲了</div>
<custom-el v-if="show">
<span>測試測試測試</span>
</custom-el>
</div>
<script>
//監聽全局異常
Vue.config.errorHandler = function (err, vm, info) {
console.log(err)
}
//自定義元素,用於測試銷燬元素生命週期
Vue.component("custom-el",{
data:function(){
return {
msg:'dddddddd'
}
},
created:function(){
//拋出錯誤,驗證 異常捕獲鉤子
throw new Error("測試異常捕獲鉤子")
},
template:`
<div>
<span>{{msg}}</span>
<slot></slot></div>
`
})
var app = new Vue({
el:"#app",
data:function(){
return {
birthday:'2010-10-10',
show:true
}
},
beforeCreate:function(){
//建立以前,沒法拿到 $data 與 $el
console.log("beforeCreate")
console.log(this.birthday)
console.log(this.$el)
},
created:function(){
//建立以前,只能拿到$data ,但沒法拿到$el
console.log("created")
console.log(this.birthday)
console.log(this.$el)
},
beforeMount:function(){
//掛載以前,能夠拿到$data與$el,可是$el是未解析的虛擬dom
console.log("beforeMount")
console.log(this.birthday)
console.log(this.$el)
},
mounted:function(){
console.log(this)
//掛載以後,能夠拿到$data與$el,此時$el爲已被解析的真實dom
console.log("beforeMount")
console.log(this.birthday)
console.log(this.$el)
},
beforeUpdate:function(){
//在$data已經修改,可是組件dom並未更新渲染時調用
console.log("beforeUpdate")
console.log(JSON.stringify(this.$data))//新的數據
console.log(this.$el.innerHTML)//原始dom
},
updated:function(){
//在$data已經修改,組件dom已被從新渲染以後調用
console.log("updated")
console.log(JSON.stringify(this.$data))//新的數據
console.log(this.$el.innerHTML)//新的dom,不能保證全部子組件被從新渲染
this.$nextTick(function(){
console.log(this.$el.innerHTML)//新的dom,能夠保證全部子組件被從新渲染了
})
},
//此處存在問題,並未驗證出來beforeDestroy與destroyed的區別
beforeDestroy:function(){
//實例銷燬以前被調用,這一步,實例仍然徹底可用
console.log("beforeDestroy")
this.birthday = '2014-11-11'
},
destroyed:function(){
//Vue 實例銷燬後調用。調用後,Vue 實例指示的全部東西都會解綁定,
//全部的事件監聽器會被移除,全部的子實例也會被銷燬。
console.log("destroyed")
},
errorCaptured:function(err,vm,info){
//當捕獲一個來自子孫組件的錯誤時被調用
console.error(err)
//若是返回false,則會阻止錯誤繼續向上傳播,不然會被全局errorHandler捕獲
return true;
},
methods:{
},
computed:{
getAge:function(){
if(this.birthday){
let date = new Date();
let birth = new Date(this.birthday)
let m1 = date.getMonth()
let m2 = birth.getMonth()
let et = m1>m2?0:1
if(m1==m2 && data.getDate() > birth.getDate()){
et = 0;
}
return date.getFullYear() - birth.getFullYear() - et
}
return 0;
}
},
filters:{
}
})
</script>
</body>
</html>
複製代碼