9.生命周期函数

生命周期函数,也叫生命周期钩子,是指组件挂载以及组件销毁所触发的一系列的方法。

 在components目录下新建Life.vue组件,用于演示生命周期函数

<template>
    <div>
        <h2>{{msg}}</h2>
        
    </div>
</template>
<script>
export default {
  name: 'life',  
  data () {
    return {
        msg:'生命周期函数演示'
    }
  },
  methods:{},
  beforeCreate(){
      console.log('实例创建之前')
  },
  created(){
      console.log('实例创建完成(常用,用于从后台获取数据后。)')
  },
  beforeMount(){
      console.log('模板编译之前')
  },
  mounted(){
      console.log('模板编译完成')
  },
  beforeUpdate(){
      console.log('数据更新之前')
  },
  updated(){
      console.log('数据更新完毕')
  },
  beforeDestroy(){
      console.log('实例销毁之前')
  },
  destroyed(){
      console.log('实例销毁完成')
  }
  
}
</script>
<style lang="scss" scoped>
h2{
    color: green;
}
</style>

在Home.vue组件内引用

<template>
    <div>
        <h2>这是一个首页组件</h2>
        <button @click="run">弹出首页组件提示</button>
        <v-life v-if="flag"></v-life>
        <br>
        <button @click="gua()">挂载卸载实例组件</button>
    </div>
</template>
<script>
import Life from './Life.vue';
export default {
  name: 'home',  
  data () {
    return {
        msg:'首页组件',
        flag:true
    }
  },
  methods:{
    run(){
        alert(this.msg)
    },
    gua(){
      this.flag=!this.flag
    }
  },
  components:{
    'v-life':Life
  }

}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>
原文地址:https://www.cnblogs.com/xuepangzi/p/11616600.html