vue组件生命周期详解

2019-11-16,,,

本文实例为大家分享了vue组件生命周期的具体代码,供大家参考,具体内容如下

分为4个阶段:

create/mount/update/destroy

每一个阶段都对应着有自己的处理函数

create: beforeCreate created

初始化

mount: beforeMount mounted

和挂载相关的处理

update: beforeUpdate updated

根据要更新的数据 做逻辑判断

destroy:beforeDestroy destroyed

清理工作

代码:

<!doctype html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>生命周期</title>
 <script src="js/vue.js"></script>
 </head>
 <body>
 <div id="container">
  <p>{{msg}}</p>
<!--点击的时候isShow进行取反 -->
  <button @click="isShow = !isShow">切换是否显示组件</button>
  <my-component v-if="isShow"></my-component>
 </div>
 <script>
  Vue.component("my-component",{
   template:`
     <div>
      <button @click="handleClick">Click Me</button>
      <h1>component:{{count}}</h1>
      </div>
   `,
   data:function(){
     return {
      count:0
     }
    },
   methods:{
    handleClick:function(){
     this.count++;
    }
   },
   beforeCreate: function () {
   console.log('准备创建组件');
  },
  created: function () {
   console.log('组件创建完毕');
  },
  beforeMount: function () {
   console.log('组件的模板准备挂载到DOM');
  },
  mounted: function () {
   console.log('挂载完毕');
  },
  beforeUpdate: function () {
   console.log('准备更新了');
  },
  updated:function(){
   console.log('更新完成');
  },
  beforeDestroy: function () {
   console.log('准备destroy');
  },
  destroyed: function () {
   console.log('destroy完成');
  }
  })
  new Vue({
   el:"#container",
   data:{
    msg:"Hello VueJs",
    isShow:true
   }
  })
 </script>
 </body>
</html>

生命周期练习,需要那阶段写那个阶段

<!doctype html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>生命周期练习</title>
 <script src="js/vue.js"></script>
 </head>
 <body>
 <div id="container">
  <p>{{msg}}</p>
  <my-component></my-component>
 </div>
 <script>
  Vue.component("my-component",{
   data:function(){
    return {
     myOpacity:0
    }
   },
   template:` <h1 v-bind:style="{opacity:myOpacity}">透明度将改变
   </h1>`,
   mounted:function(){
    setInterval(function(){
     this.myOpacity += 0.1;
     if(this.myOpacity>1){
      this.myOpacity = 0;
     }
    }.bind(this),1000)
   }
  })
  new Vue({
   el:"#container",
   data:{
    msg:"Hello VueJs"
   }
  })
 </script>
 </body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • Vue实例中生命周期created和mounted的区别详解
  • 详解Vue 实例中的生命周期钩子
  • 深入理解Vue生命周期、手动挂载及挂载子组件
  • Vue 2.0中生命周期与钩子函数的一些理解
  • Vue.js实例方法之生命周期详解
  • Vuejs入门教程之Vue生命周期,数据,手动挂载,指令,过滤器
  • Vue2.0生命周期的理解
  • vue生命周期和react生命周期对比【推荐】
  • 基于Vue实例生命周期(全面解析)
  • Vue的生命周期操作示例

《vue组件生命周期详解.doc》

下载本文的Word格式文档,以方便收藏与打印。