首頁 > 軟體

詳解Vue 自定義hook 函數

2022-06-15 14:00:20

定義

什麼是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 內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com