天天看点

Vue.js学习(8)-生命周期函数

1.生命周期函数

生命周期函数也叫生命周期钩子,是组件创建,组件销毁,组件更新时执行的方法,一共有8个,常用的是mounted,destroyed

beforeCreate(){

      console.log("实例创建前");

    },

    created(){

      console.log("实例已创建");

    },

    beforeMount(){

      console.log("实例编译前");

    },

    mounted(){  

      console.log("实例已编译");

    },

    beforeUpdate(){

      console.log("实例更新前");

    },

    updated(){

      console.log("实例已更新");

    },

    beforeDestroy(){  

      console.log("实例销毁前");

    },

    destroyed(){

      console.log("实例已销毁");

    }

Vue.js学习(8)-生命周期函数

2.生命周期函数实现的实例

Life.vue

<template>
  <div>
    生命周期函数的演示   -----{{msg}}
    <br>
    <hr>
    <button @click="setMsg()">执行方法改变msg</button>
  </div>
</template>

<script>
  export default {
    name: "Life",
    data(){
      return{
        msg:"msg",
      }
    },
    methods:{
      setMsg(){
        this.msg = "这是一个msg改变后的数据";
      }
    },
    beforeCreate(){
      console.log("实例创建前");
    },
    created(){
      console.log("实例已创建");
    },
    beforeMount(){
      console.log("实例编译前");
    },
    mounted(){  /* 请求数据放在这个里面 操作数据 必须记住 mounted*/
      console.log("实例已编译");
    },
    beforeUpdate(){
      console.log("实例更新前");
    },
    updated(){
      console.log("实例已更新");
    },
    beforeDestroy(){  /*页面销毁的时候要保存一些数据,就可以监听这个销毁的生命周期函数*/
      console.log("实例销毁前");
    },
    destroyed(){
      console.log("实例已销毁");
    }

  }
</script>

<style scoped>

</style>
           

导入组件

import Life from "./Life.vue";
           

注册组件

components:{
       "v-life":Life
      }
           

使用组件

<v-life v-if="flag"></v-life>
      <br>
      <button @click="flag =!flag">挂载与卸载Life组件</button>
           

运行组件

Vue.js学习(8)-生命周期函数
Vue.js学习(8)-生命周期函数
Vue.js学习(8)-生命周期函数

继续阅读