Skip to content

Vue3的hook函数和toRef函数

1. hook函数

  • 什么是hook? ---本质是一个函数,把setup函数中使用的Composition API进行了封装
  • 类似于Vue2中的mixin
  • 自定义hook的优势: 复用代码,让setup中的逻辑更清楚易懂。 增加hooks文件夹 Alt text
js
import { reactive, onMounted, onUnmounted } from 'vue'

export default function usePoint(){
    let position = reactive({
        X:0,
        Y:0
    })
    function addPoint(event){
        console.log('---addPoint----');
        position.X = event.screenX
        position.Y = event.screenY
    }
    onMounted(()=>{
        window.addEventListener('click', addPoint)
    })
    onUnmounted(()=>{
        window.removeEventListener('click', addPoint)
    })
    return position
}
vue
<template>
  <h2> 鼠标坐标 X: {{ position.X }}    Y: {{ position.Y }}</h2>
</template>

<script>
import usePoint from "../hooks/UsePoint";
export default {
  name: 'Test',
  setup() {
    let position = usePoint()
    return {
      position
    }
  }
}   
</script>
<style scoped>
</style>

2. toRef函数

作用:创建一个ref对象,其value值指向另一个对象中的某个属性。
语法:const name = toRef(person, 'name')
应用:要将响应式对象中的某个属性单独提供给外部使用时。因此可以在模版中简写
扩展:toRefs与toRef功能一致, 但可以批量创建多个ref对象, 语法:toRefs(person)

js
let age = toRef(person, 'age')
console.log('@@@', age)

Alt text