vue-初识生命周期

79 阅读1分钟

生命周期:

  1. 又名:生命周期回调函数、生命周期函数、生命周期钩子。
  2. 是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。
  3. 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。
  4. 生命周期函数中的this指向是vm 或 组件实例对象。
munted生命周期.png

生命周期函数与data、methods...属性平级

mounted(){}生命周期函数:
在vue完成模板的解析并把初始的真实Dom元素放入页面后(挂载完毕)调用methods
image.png

<div id="root">
    <h1 :style="{opacity:n}">{{name}}</h1>
</div>

const vm = new Vue({
  el: '#root',
  data: {
    name: "hello word",
    n: 1,
  },
  mounted() {
    setInterval(() => {
      this.n = this.n - 0.01;
      if (this.n <= 0) {
        this.n = 1;
      }
    }, 18)
  }
})

生命周期函数:执行顺序按代码顺序排序

<div id="root" :x="n">
    <h2 v-text="n"></h2>
    <h2>当前的n值是:{{n}}</h2>
    <button @click="add">点我n+1</button>
    <button @click="bye">点我销毁vm</button>
</div>

new Vue({
    el:'#root',
    data:{
        n:1
    },
    methods: {
        add(){
            console.log('add')
            this.n++
        },
        bye(){
            console.log('bye')
            this.$destroy()
        }
    },
    beforeCreate() {
        console.log('beforeCreate')
    },
    created() {
        console.log('created')
    },
    beforeMount() {
        console.log('beforeMount')
    },
    mounted() {
        console.log('mounted')
    },
    beforeUpdate() {
        console.log('beforeUpdate')
    },
    updated() {
        console.log('updated')
    },
    beforeDestroy() {
        console.log('beforeDestroy')
    },
    destroyed() {
        console.log('destroyed')
    },
})

图解生命周期函数执行过程:

生命周期.png