vue3 | 使用hook函数

93 阅读1分钟

一周大事件公众号封面首图__2024-02-05+172558.jpeg

什么是Hook?

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

自定义Hook

hooks 文件,新建useAdd.js

import {ref, watch} from 'vue'

const useAdd =  ({num1,num2} ) => {
  const result = ref(0)

  // 监听num1和num2的变化
  watch([num1,num2],([newNum1,newNum2])=>{
    result.value = newNum1 + newNum2
  })

  // 定义addFunc函数
  const addFunc = (num1, num2) => {
    result.value = num1 + num2
  }
  
  // 返回result和addFunc
  return {
    result,
    addFunc
  }
}

export default useAdd

组件中使用hook

<template>
  <div>
    <h3>我是UserHook组件</h3>
    <h4>使用加法</h4>
    <div>
      num1:<input v-model.number="num1" style="width:100px" />
      <br />
      num2:<input v-model.number="num2" style="width:100px" />
    </div>
    <span>加法等于:{{ result }}</span>
  </div>
</template>

<script setup>
import useAdd from "../hooks/useAdd";
import {useCut} from "../hooks/useCut";
import { reactive, computed, ref } from "vue";


const num1 = ref(0);
const num2 = ref(0);
const num3 = ref(0);
const num4 = ref(0);
const { result } = useAdd({ num1, num2 });

</script>