温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue组件生有哪些命周期

发布时间:2021-07-09 14:32:23 来源:亿速云 阅读:102 作者:Leah 栏目:web开发

本篇文章给大家分享的是有关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>
      <h2>component:{{count}}</h2>
      </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:` <h2 v-bind:>透明度将改变
   </h2>`,
   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组件生有哪些命周期,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI