head部分:
<script type="text/javascript" src="bower_components/vue/dist/vue.min.js"></script>
body部分的html代碼:
<!--組件的生命周期有八個,點乘式為[create,mount,update,destroy] x [before,ed]--> <div id="app"> <newcomponent1 v-if="show"></newcomponent1> <!--button用來銷毀和創建組件--> <button @click="ifShow">創建/銷毀</button> </div>
script部分的代碼:
<script> new Vue({ el:"#app", data:{ show:true }, components:{ "newcomponent1":{ //vue2.0中只允許template只存在一個元素,多種元素組合就得包裹在一個盒子里面 template:'<div><p>{{message}}</p><br/><button @click="message++">+1</button></div>', data:function(){ return {message:0}; }, beforeCreate:function(){ //別想着在這里調用methods的方法了,不可能的,盤古還沒開天地,你咋抬頭都看不見天。 //其實我們可以把整個vue實例看做一個組件,以便於我們理解vue的生命周期 console.log("called before create!") }, created:function(){ this.createdFun(); }, beforeMount:function(){ this.beforeMounteFun(); }, mounted:function(){ this.muntedFun(); }, beforeUpdate:function(){ this.beforeUpdateFun(); }, updated:function(){ this.updatedFun(); }, beforeDestroy:function(){ this.beforeDestroyFun(); }, destroyed:function(){ this.destroyedFun(); },methods:{ //beforeCreateFun:function(){ // console.log("called before create!") //},為什么注釋掉,因為beforeCreate取不到內部的任何數據 createdFun:function(){ console.log("called created!") },beforeMounteFun:function(){ console.log("called before mounte!") },muntedFun:function(){ console.log("called mounted!") },beforeUpdateFun:function(){ console.log("called before update!") },updatedFun:function(){ console.log("called updated!") },beforeDestroyFun:function(){ console.log("called before destroy!") },destroyedFun:function(){ console.log("called distroy!"); } } } }, methods:{ ifShow:function(){ this.show = !this.show; } } }); </script>