vue生命周期

export default({
 data:function(){
  return {username:"popo",num:0} 
 },
 methods:{
   change(){
     this.username="hahah"
   },
 
 },
   //创建阶段
  //  第一阶段 beforeCreate 此时props data methods 还没有创建,都不可用
   beforeCreate(){
     console.log("beforeCreate阶段");
     console.log(this.username); //会输出undefined
   },
   //第二阶段 created  此时data以及方法等都可以加载出来了 但是模板还未加载, 此时最好发送ajax请求拿数据
  created(){
     console.log("created阶段");
     console.log(this.username);
     console.log(this.change); 
     var xhr=new XMLHttpRequest();
     xhr.open("get","https://ku.qingnian8.com/wxList.php");
    var that=this
     xhr.onreadystatechange=function(){
       if(xhr.readyState==4){


       that.num=JSON.parse(xhr.responseText).length;
       }
     }
     xhr.send()


   },
  //  第三阶段 beforeMount阶段准备生成Dom,但没有渲染到页面呢
  beforeMount(){
    console.log("beforeMount");
     console.log(this.username); 


  },
  //  第四阶段 Mounted阶段渲染到页面,可以拿到dom节点了!
  //正是第一次操作dom的好时候

  mounted(){
    var head=document.querySelector("#head")
    console.log("Mounted");
    console.log(head);

  },
  // 运行阶段
  //beforeUpdate阶段 数据变化触发 但此时数据变成了最新数据,但是DOM还没有更新
  // 打开页面就会触发 而且输出的数据为0 
  //原因:在created阶段就改变了数据 改变数据就会触发beforeUpdate 
  //而此函数触发只能拿到最新数据 num=9,但是页面的dom结构是旧的 所谓 innerHTML拿到的是0
  beforeUpdate(){
    console.log("beforeUpdate");
    var head=document.querySelector("#head")
    console.log(this.num);
    console.log(head.innerHTML);


  },
  //Updated阶段 数据变化触发 但此时数据变成了最新数据,但是DOM也进行了更新

  updated(){
 console.log("Updated");
    var head=document.querySelector("#head")
    console.log(this.num);
    console.log(head.innerHTML);
  },
 components:{
   Left,
   Right
 }
})

 

 

posted @ 2021-08-22 20:31  冰镇汽水  阅读(35)  评论(0)    收藏  举报