詳解Vue 自定義hook 函數

定義

什麼是hook?

  • 本質是一個函數,把 setup 函數中使用的 Composition API (組合API)進行瞭封裝
  • 類似於 vue2.x 中的 mixin

自定義 hook 的優勢:

  • 復用代碼,讓 setup 中的邏輯更清楚易懂

使用

首先我們做一個功能,鼠標點擊屏幕,獲取坐標:

<template>
  <h2>當前鼠標的坐標是:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import {onMounted, onBeforeUnmount,reactive} from 'vue'

export default {
  name: 'Demo',
  setup() {
    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,
    }
  },
}
</script>

然後改用使用 hooks,在 src 下新建 hooks 文件夾,增加 usePoint.js

import {onBeforeUnmount, onMounted, reactive} from "vue/dist/vue";
function savePoint() {
    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
}
export default savePoint;

或者簡寫:

......
export default function() {
    ......
}

在 Demo.vue 中使用:

<template>
  <h2>當前鼠標的坐標是:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import usePoint from "@/hooks/usePoint";
export default {
  name: 'Demo',
  setup() {
    let point = usePoint()

    return {
      point
    }
  },
}
</script>

封裝發ajax請求的hook函數(ts版本)

hooks 下新建 useRequest.ts

由於用到瞭 axios,所以安裝axios:npm install axios

import {ref} from "vue";
import axios from "axios";
export default function <T>(url: string) {
    const loading = ref(true);
    const data = ref<T | null>(null);
    const errorMsg = ref('');
    axios.get(url).then(response => {
        loading.value = false
        data.value = response.data
    }).catch(error => {
        loading.value = false
        errorMsg.value = error.message || '未知錯誤'
    })
    return {
        loading,
        data,
        errorMsg
    }
}

App.vue:

<template>
  <h3 v-if="loading">加載中...</h3>
  <h3 v-else-if="errorMsg">錯誤信息:{{errorMsg}}</h3>
  <!-- 對象 -->
  <ul v-else>
    <li>{{data.name}}</li>
    <li>{{data.address}}</li>
    <li>{{data.distance}}</li>
  </ul>
  <!-- 數組 -->
  <ul v-for="item in data" :key="item.name">
    <li>{{item.name}}</li>
    <li>{{item.address}}</li>
    <li>{{item.distance}}</li>
  </ul>
</template>
<script lang="ts">
import {defineComponent, watch} from 'vue';
import useRequest from "@/hooks/useRequest";

export default defineComponent({
  setup() {
    // 定義接口
    interface IAddress{
      name:string,
      address:string,
      distance:string
    }
    //const {loading,data,errorMsg} = useRequest<IAddress>("./address.json")//獲取對象數據
    const {loading,data,errorMsg} = useRequest<IAddress[]>("./addressList.json")//獲取對象數據
    watch(data, () => {
      if (data.value) {
        console.log(data.value.length)
      }
    })
    return {
      loading,
      data,
      errorMsg
    }
  }
});
</script>

測試數據有對象類型的 address.json:

{
  "name": "傢",
  "address": "開發區人民路22號",
  "distance": "100km"
}

還有數組類型的 addressList.json

到此這篇關於詳解Vue 自定義hook 函數的文章就介紹到這瞭,更多相關Vue 自定義hook 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: