1. 引入vue.js庫
<script src="https://cdn.bootcss.com/vue/2.2.1/vue.min.js"></script>
2. html
<div id="app">
<template>
<div>
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
<hr>
<button onclick="vm.$destroy()">此按鈕用來銷毀實例</button>
</div>
</template>
</div>
3. script
注意:
1. 最常用的就是前四個生命周期鉤子beforeCreate、created、 beforeMount、mounted
2. 生命周期里面的activated和deactivated我這里沒有做演示,只寫了大概意思
Vue.component('button-counter', {
template: '<button v-on:click="increment">我是按鈕{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods:{
increment: function () {
this.counter += 1
this.$emit('increment')
}
}
})
var vm = new Vue({
el:'#app',
data() {
return{
total: 0
}
},
methods: {
incrementTotal(){
this.total += 1
}
},
// 組件的生命周期
beforeCreate(){ //在實例創建之后,在數據初始化之前被調用
alert('1-beforeCreate');
},
created(){ // 在數據初始化之后被調用,如果你的頁面進來的時候就調用接口,那么created是第一選擇
alert('2-created');
},
beforeMount(){ //在組建渲染之前被調用,也就是說數據渲染之前,比如要色彩渲染可以在這里寫
alert('3-beforeMount');
},
mounted(){//整個實例被創建完成后被調用,比如:實例創建完成、數據初始化、渲染頁面數據后,才被調用,這個時候就可以在mounted這個生命周期里面寫Dom操作了,注意:生命周期用的最多的就是mounted
alert('4-mounted');
},
beforeUpdate(){ //在數據改變時被調用,比如: total = 0 , 然后手動把num++; 就會執行此方法
alert('5-beforeUpdate');
},
updated(){ //數據被更新之后, 比如:total值改變之后,再被執行
alert('6-updated');
},
activated(){ //keep-alive 組件激活時調用,也就是說在路由切換時被調用,注意要配合keep-alive使用才會被調用
alert('7-activated');
},
deactivated(){//keep-alive 組件停用時調用,也可以理解成在路由切換的會自動停用組件,
alert('8-deactivated');
},
beforeDestroy(){//實例銷毀之前被調用,這個方法適用于 把new Vue({})賦值給一個變量時,如: var vm = new Vue({}),然后用vm.$destroy() 方法銷毀這個實例
alert('9-beforeDestroy');
},
destroyed(){//實例銷毀之后被調用,一般情況下,在頁面切換路由時,會自動銷毀組件,
alert('10-destroyed');
}
})
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。