当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue组件生命周期详解

vue组件生命周期详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

法网群英好看吗,caoliu 高圆圆,远离邪教手抄报

本文实例为大家分享了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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网