The hooks function is similar to mixins in vue2
video
src\App.vue
<template>
<h2>Custom hook function operations</h2>
<h2>x:{{x}},y:{{y}}</h2><hr> <! -- Object data --><h3 v-if="loading">Loading...</h3>
<h3 v-else-if="errorMsg">Error message :{{errorMsg}}</h3>
<ul v-else>
<li>id:{{data.id}}</li>
<li>address:{{data.address}}</li>
<li>distance:{{data.distance}}</li>
</ul><hr> <! -- Array data --><ul v-for="item in data" :key="item.id">
<li>id:{{item.id}}</li>
<li>title:{{item.title}}</li>
<li>price:{{item.price}}</li>
</ul></template> <script lang="ts"> import { defineComponent, Watch} from 'vue' import useMousePosition from './hooks/useMousePosition' // Request method wrap import useRequest From './hooks/useRequest' // define interface, constraint object type interface IAddressData {ID: number address: string distance: string } interface IProductData { id: number title: string price: number } export default defineComponent({ name: 'App', setup() {const {x, y} = useMousePosition() ErrorMsg} = useRequest<IAddressData>('/data/address.json') // Array data const {loading, data, errorMsg } = useRequest<IProductData[]>( '/data/products.json' ) watch(data, () => { if (data.value) { console.log(data.value.length) } }) return { x, y, loading, data, errorMsg } }, }) </script>Copy the code
src\hooks\useMousePosition.ts
import { onBeforeUnmount, onMounted, ref } from 'vue'
export default function() {
const x = ref(-1)
const y = ref(-1)
// Click the event callback function
const clickHandler = (event: MouseEvent) = > {
x.value = event.pageX
y.value = event.pageY
}
// Add the event when the page is loaded
onMounted(() = > {
window.addEventListener('click', clickHandler)
})
// Unmount the event before the page unmounts
onBeforeUnmount(() = > {
window.removeEventListener('click', clickHandler)
})
return { x, y }
}
Copy the code
src\hooks\useRequest.ts
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 || 'Unknown error'
})
return { loading, data, errorMsg }
}
Copy the code
public\data\address.json
{
"id": 1."address": Songjiang District, Shanghai."distance": "1000m"
}
Copy the code
public\data\products.json
[{"id": "001"."title": Huawei Mobile."price": 3000
},
{
"id": "002"."title": "Xiaomi Phone"."price": 2000}]Copy the code