九、自定义组合式函数

郁子小于 1 分钟约 182 字笔记Vue3尚硅谷张天禹

Vue3 组合式函数open in new window

Hooks 时代,如何写出高质量的 react 和 vue 组件?open in new window

手摸手教你封装几个 Vue3 中很有用的组合式 APIopen in new window

(一)定义

  • 本质是一个函数,把 setup 函数中使用的 Composition API 进行了封装
  • hooks 的文件一般命名为:useXxxx.js

(二)类比

  • 类似于 Vue2.x 中的 mixin

(三)优势

  • 复用代码,让 setup 中的逻辑更清楚易懂

(四)使用

// hooks/useXXX.js
import XXX from "XXX";

export function useXXX() {
  const a = ref(0);

  let b = computed(() => {
    return "test";
  });

  function changeA(val) {
    a.value = val;
  }

  return {
    a,
    b,
    changeA,
  };
}
<!-- test.vue -->
<script setup>
  import {useXXX} from "../hooks/useXXX";
  const {(a, b, changeA)} = useXXX();
</script>
上次编辑于: