556、Vue 3 学习笔记 -【常用Composition API(五)】 2023.08.25

本文介绍了Vue3中的生命周期更新,包括传统钩子的更名与组合式API的对应关系。同时,讲解了如何使用自定义hook封装setup函数和toRef用于创建响应式ref对象,以及toRefs的批量创建功能。
摘要由CSDN通过智能技术生成

一、生命周期

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

  • beforeDestroy改名为beforeUnmount
  • destroy改名为unmounted

Vue3也提供了组合式API形式的生命周期钩子,与Vue2中钩子对应关系如下:

  • beforeCreate ===> setup()
  • created ===> setup()
  • beforeMount ===> onBeforeMount
  • mounted ===> onMounted
  • beforeUpdate ===> onBeforeUpdate
  • updated ===> onUpdated
  • beforeUnmount ===> onBeforeUnmount
  • unmounted ===> onUnmounted
 import {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from 'vue'
    
    setup(){
        let sum = ref(20)
        // 通过组合式API的形式去使用生命周期钩子
        onBeforeMount(()=>{
            console.log('---onBeforeMount---')
        })
        
        onMounted(()=>{
            console.log('---onMounted---')
        })
        
        onBeforeUpdate(()=>{
            console.log('---onBeforeUpdate---')
        })
        …………        
    }

二、自定义hook函数

  • 什么是hook? —— 本质是一个函数,把setup函数中使用的Composition API进行了封装。
  • 类似于vue2.x中mixin。
  • 自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂。

创建一个js文件,比如usePoint.js ,内容:

import {reactive, onMounted, onBeforeUnmount} from 'vue'
    export default function(){
        let point = reactive({
            x:0,
            y:0
        })
        // 获取鼠标点击坐标
        function savePoint(event){
            point.x = event.pageX
            point.y = event.pageY
        }
        onMounted(()=>{
            window.addEventListener('click', savePoint)    
        })        
        onBeforeUnmount(()=>{
            window.removeEventListener('click', savePoint)
        })          
        return point
    }

在vue文件中引入userPoint.js

   <p>鼠标点击坐标 x:{{point.x}}  y:{{point.y}}<p>
    
    import usePoint from '/hook/usePoint.js' 
    
    setup(){
        let point = usePoint()
        
        return { point }
    }

三、toRef

  • 作用:创建一个ref对象,其value值指向另一个对象中的某个属性。
  • 语法:const name = toRef(person, ‘name’)
return {
        name: toRef(person,'name')
        salary: toRef(person.job.j1, 'salary')
    }
  • 应用:要将响应式对象中的某个属性单独提供给外部使用时。
  • 扩展:toRefs 与 toRef 功能一致,但可以批量创建多个ref对象,语法:toRefs(person)
 // person中的salary属性用法
    <p> {{ job.j1.salary }} </p>
    return {
        // 把person属性都拆开
        ...toRefs(person)
    }

四、参考链接

[01] Vue3学习笔记(尚硅谷)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值