Vue入門(6)生命週期

在這裏插入圖片描述

<div id="app">
	<App></App>
</div>
<script>
       Vue.component("Tset",{
           data(){
               return {
                   msg : "hello"
               }
           },
           template : `
               <div>
                   <h3>{{msg}}</h3>
                   <button @click="changeHanlder"></button>
               </div>
           `,
           methods : {
               changeHanlder(){
                   this.msg = this.msg + "哈哈哈😄"
               }
           },
           beforeCreate : function(){
               //組件創建之前
               console.log(this.msg);//undefined
           },
           created : function(){
               console.log(this.msg);//hello
               //組件創建之後,使用該組件,就會調用created方法
               //created方法中可以操作後端的數據,數據驅動視圖
               //應用:發起ajax請求
           },
           beforeMount : function(){
               //掛載數據到dom之前調用
               console.log(document.getElementById("app"));
           },
           mounted : function(){
               //掛載數據到dom之後調用
               //應用:操作dom
               console.log(document.getElementById("app"));
           },
           beforeUpdate : function(){
               //更新dom之前調用,應用:獲取原始dom
               console.log(document.getElementById("app").innerHTML);
               //<div class="app"><div><h3>hello</h3> <button></button></div></div>
           },
           updated : function(){
               //更新dom之後調用,應用:獲取最新的dom
               console.log(document.getElementById("app").innerHTML);
               //<div class="app"><div><h3>hello哈哈哈😄</h3> <button></button></div></div>
           },
           beforeDestroy : function(){
               //實例銷燬之前調用。在這一步,實例仍然完全可用。
               console.log("beforeDestroy");
           },
           destroyed : function(){
               //Vue 實例銷燬後調用。調用後,Vue 實例指示的所有東西都會解綁定,所有的事件監聽器會被移除,所有的子實例也會被銷燬。
               console.log("destroyed");
           },
           activated :function(){
               //keep-alive 組件激活時調用。
               console.log("組件被激活了");
           },
           deactivated :function(){
               //keep-alive 組件停用時調用。
               console.log("組件停用了了");
           }
       })

       var App = {
           data(){
               return {
                   isShow : true
               }
           },
           //vue內置組件<keep-alive></keep-alive>能在組件的切換過程中將狀態保留在內存中
           //防止重複渲染dom
           template : `
               <div class="app">
                   <keep-alive>
                       <Tset v-if="isShow"/>
                   </keep-alive>   
                   <button @click="isShow=!isShow">改變生死</button>
               </div>
           `
       }

       new Vue({
           el: '#app',
           data: {
               
           },
           components : {
               App
           }
       })
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章