vue生命周期

每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会

生命周期钩子的 this 上下文指向调用它的 Vue 实例。不要在选项属性或回调上使用箭头函数
比如 created: () =>console.log(this.a)vm.$watch('a', newValue => this.myMethod())。因为箭头函数并没有 this,this 会作为变量一直向上级词法作用域查找,直至找到为止,经常导致Uncaught TypeError: Cannot read property of undefinedUncaught TypeError: this.myMethod is not a function 之类的错误

生命周期图解在这里插入图片描述
在这里插入图片描述

<template>
  <div id="app">
      <div @click="bg+=1"> {{bg}}</div>
      <button @click="handleDestroy">销毁</button>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  name: "app",
  data() {
    return {
      bg:2020
    };
  },
  methods: {
    handleDestroy(){
      this.$destroy();
    }
  },
  beforeCreate(){
    console.log(this.bg);
    console.log("beforecreate--data和methods还未初始化");
  },
  created(){
    console.log(this.bg);
    console.log("created--已经初始化好,要操作data和methods数据,最早可以在这里进行");
  },
  beforeMount(){
    console.log(this.bg);
    console.log("beforemount--挂载前模板已编译好,但未渲染到页面");
  },
  mounted() {
    console.log(this.bg);
    console.log("mounted--已渲染到页面,该函数一执行完,就脱离了创建状态,到运行状态");
  },
  beforeUpdate(){
    console.log(this.bg);
    console.log("beforeupdated--页面数据还是旧的");
  },
  updated(){
    console.log(this.bg);
    console.log("updated--数据是新的");
  },
  beforeDestroy() {
    this.bg=this.bg+1
     console.log(this.bg);
    console.log("beforeDestroy--数据销毁");
  },
  destroyed(){
     console.log(this.bg+1);
    console.log("Destroy--数据销毁,之后不能再继续操作");
  }

  }
</script>

<style lang="less" scope>
* {
  padding: 0;
  margin: 0;
}
#app {
  width: 700px;
  min-height: 300px;
  margin: auto;
  .dis {
    width: 200px;
    height: 100px;
    background-color: pink;
  }
}
</style>

在这里插入图片描述
在这里插入图片描述
销毁之后就不能再操作了
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值