Hook函数&生命周期

创建hook文件夹,和components同级,底下创建.js文件,以use开头,useCar.js导出一个函数
import { ref, computed } from "vue";
export default function () {
    let carName = ref("奔驰");
    let carPrice = ref(200000);
    let updateCarName = (name) => {
        carName.value = name;
    }
    let updateCarPrice = (price) => {
        carPrice.value = price;
    }
    let usaCarPrice = computed(() => {
        return '$' + (carPrice.value / (Math.random() + 6)).toFixed(2)
    })
    return {
        carName,
        carPrice,
        updateCarPrice,
        updateCarName,
        usaCarPrice
      };
}
导入useCar.js文件
import useCar from '../hooks/useCar.js'
export default {
  name: "Child",
  setup() {
    return {
        ...useCar(),
        ...usePlane()
    };
  },
};

生命周期

vue2

beforeCreate() {
    // 数据初始化前
},
created() {
    //数据初始化完成
},
beforeMount() {
    //数据初始化完成,页面未挂载前
},
mounted() {
    //数据挂载页面完成
},
beforeUpdate() {
    //数据修改后,页面数据重新挂载前
},
updated() {
   //数据修改后,页面数据重新挂载完成
},
beforeDestroy() {
    //数据销毁前
},
destroyed() {
    // 数据销毁后
}

vue3

除了beforeCreate和created两个生命周期函数没有组合式API,因为setup函数充当了beforeCreate和created两个生命周期函数,其他的生命周期函数都有对应的组合式API,命名方式是在原有方法名前面加上on。
注意:setup是在beforeCreate和created两个生命周期函数之前运行的,所以在setup里面,无法调用data和methods里面的数据
<script>
import {ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated, onBeforeUnmount, onUnmounted  } from 'vue'
export default {
name:'Child3',

setup() {
    let count=ref(1)
    let updateCount=()=>{
        count.value++
    }
    onBeforeMount(() => {
       //挂在前
        console.log(onBeforeMount);
    })
    onMounted(() => {
         //挂在完成
        console.log(onMounted);
    })
    onBeforeUpdate(() => {
   //修改后,页面重新挂载前
        console.log(onBeforeUpdate);
    })
    onUpdated(() => {
    //修改后,页面重新挂载完成
        console.log(onUpdated);
    })
    onBeforeUnmount(() => {
     //卸载前
        console.log(onBeforeUnmount);
    })
    onUnmounted(() => {
    //卸载完成
        console.log(onUnmounted);
    })

    return{
      count,updateCount ,onBeforeMount ,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted
    }
}
}
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容