生命周期

生命周期

  • Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:

    • beforeDestroy改名为 beforeUnmount

    • destroyed改名为 unmounted

  • Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:

    • beforeCreate===>setup()

    • created=======>setup()

    • beforeMount ===>onBeforeMount

    • mounted=======>onMounted

    • beforeUpdate===>onBeforeUpdate

    • updated =======>onUpdated

    • beforeUnmount ==>onBeforeUnmount

    • unmounted =====>onUnmounted

 

  vue3.x可以同时使用配置项的API,也可以使用组合式的API

  有2个声明周期被改名字[上面] ; 组合式API就在配置项的API前面加上on;

  执行顺序是 setup =>  beforeCreate , created  =>  onBeforeMount  =>  beforeMount  => onMounted  => mounted =>  onBeforeUpdate  =>  beforeUpdate

        =>  onUpdated  =>  updated  =>  onBeforeUnmount  =>  beforeUnmount  =>  onUnmounted  =>  unmounted

 

父组件 : 

<template>
  <div class="about">
      <h1>父组件</h1>
      <h2 @click="ishow = !ishow">显示/隐藏</h2>
      <HelloWorld  v-if="ishow"></HelloWorld>  
  </div>
</template>
<script>
import HelloWorld from '../components/HelloWorld.vue'
import { ref } from 'vue'
export default {
  components:{HelloWorld},
  setup(){ 
    let ishow = ref(true)
    let btn = ()=>{
      ishow.value = !ishow.value
      console.log(ishow)
    }
    return {ishow}
  }
}
</script>

子组件 : 

<template>
  <div class="hello">
    <h1>子组件</h1>
  </div>
</template>

<script>
import { onBeforeMount,onMounted,onUpdated,onBeforeUpdate ,onUnmounted,onBeforeUnmount} from '_vue@3.2.33@vue';
export default {
  name: "HelloWorld",
  setup(){
    console.log('-- setup --');
    // 组合式API
    onBeforeMount(()=>{
      console.log('-- 组合式API的onBeforeMount --');
    }),
    onMounted(() => {
      console.log('-- 组合式API的onMounted --');
    }),
    onBeforeUpdate(()=>{
      console.log('-- 组合式API的onBeforeUpdate --');
    }),
    onUpdated(() => {
      console.log('-- 组合式API的onUpdated --');
    }),
    onBeforeUnmount(() => {
      console.log('-- 组合式API的onBeforeUnmount --');
    }),
    onUnmounted(() => {
      console.log('-- 组合式API的onUnmounted --');
    })
  },
  beforeCreate(){
    console.log('-- 配置项的beforeCreate --');
  },
  created(){
    console.log('-- 配置项的created --');
  },
  beforeMount(){
    console.log('-- 配置项的beforeMount --');
  },
  mounted(){
    console.log('-- 配置项的mounted --');
  },
  beforeUpdate(){
    console.log('-- 配置项的beforeUpdate --');
  },
  updated(){
    console.log('-- 配置项的updated --');    
  },
  beforeUnmount(){
    console.log('-- 配置项的beforeUnmount --');
  },
  unmounted() {
    console.log('-- 配置项的unmounted --');    
  },
};
</script>

 

posted @ 2022-05-20 10:41  杨建鑫  阅读(159)  评论(0编辑  收藏  举报