vue3的自定義hook函數(shù)使用
自定義hook函數(shù)使用
- 使用Vue3的組合API封裝的可復(fù)用的功能函數(shù)
- 自定義hook的作用類似于vue2中的mixin技術(shù)
- 自定義Hook的優(yōu)勢(shì): 很清楚復(fù)用功能代碼的來(lái)源, 更清楚易懂
- 需求1: 收集用戶鼠標(biāo)點(diǎn)擊的頁(yè)面坐標(biāo)
這里先看一下大體項(xiàng)目結(jié)構(gòu):
這里的hooks下的文件是示例代碼,public內(nèi)的是測(cè)試數(shù)據(jù)
在啟動(dòng)項(xiàng)目后,測(cè)試public的data文件內(nèi)的數(shù)據(jù),
App.vue
<template> <div> <h2>自己定義hook函數(shù)操作</h2> <h2>x:{{x}}, y:{{y}}</h2> <h3 v-if="loading">正在加載中11...</h3> <h3 v-else-if="errorMsg">{{errorMsg}}</h3> <ul v-else> <li>id:{{data.id}}</li> <li>address:{{data.address}}</li> <li>distance:{{data.distance}}</li> </ul> <!-- 數(shù)組數(shù)據(jù) --> <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> </div> </template>
<script> import { defineComponent, watch } from 'vue' import useMousePosition from './hooks/useMousePosition' import useRequest from './hooks/useRequest' export default defineComponent({ name: 'App', // 需求1:用戶在頁(yè)面中點(diǎn)擊頁(yè)面,把點(diǎn)擊位置的橫縱坐標(biāo)收集并展示起來(lái) setup(){ const {x,y} = useMousePosition() // 發(fā)送請(qǐng)求 // const {loading, data, errorMsg} = useRequest('data/address.json') // 獲取對(duì)象數(shù)據(jù) const {loading, data, errorMsg} = useRequest('data/products.json') // 獲取數(shù)組數(shù)據(jù) // 監(jiān)聽 watch(data, () => { if(data.value){ console.log(data.value.length); } }) return { x, y, loading, data, errorMsg } } }) </script>
src下hooks的 useMousePosition.ts
import { ref, onBeforeUnmount, onMounted } from 'vue' export default function () { const x = ref(-1) const y = ref(-1) // 點(diǎn)擊事件的回調(diào)函數(shù) const clickHandler = (event:MouseEvent) => { x.value = event.pageX y.value = event.pageY } // 頁(yè)面已經(jīng)加載完畢了,再進(jìn)行點(diǎn)擊操作 // 頁(yè)面加載完畢的生命 onMounted(() => { window.addEventListener('click',clickHandler) }) // 頁(yè)面卸載之前的生命周期組合Api onBeforeUnmount(() => { window.removeEventListener('click',clickHandler) }) return { x, y } }
src下hooks的 useRequest.ts
import { ref } from 'vue'; import axios from 'axios'; interface AddressData{ id: number; address:string; distance:string; } interface ProductsData{ id: string; title:string; price:number; } export default function (url:string) { // 加載的狀態(tài) const loading = ref(true) // 請(qǐng)求成功的數(shù)據(jù) // 用于數(shù)據(jù)格式替換 ProductsData const data = ref<ProductsData[] | null>(null) // 錯(cuò)誤信息 const errorMsg = ref('') // 發(fā)送請(qǐng)求 axios.get(url).then(response => { // 改變加載狀態(tài) loading.value = false data.value = response.data }).catch(error=>{ console.log(111); }) return { loading, data, errorMsg } }
public下data的 address.json
{ "id": 1, "address": "陜西西安", "distance": "100m" }
public下data的 products.json
[ { "id":"001", "title": "華為", "price": 3000 }, { "id": "002", "title": "小米12", "price": 1900 } ]
最后查看一下整體運(yùn)行展示:
vue3 hooks函數(shù)示例
以ant-design-vue 2.2.8版Upload上傳組件為例:
官方示例代碼---封裝前
<template> ? <a-upload ? ? v-model:file-list="fileList" ? ? name="file" ? ? :multiple="true" ? ? action="https://www.mocky.io/v2/5cc8019d300000980a055e76" ? ? :headers="headers" ? ? @change="handleChange" ? > ? ? <a-button> ? ? ? <upload-outlined></upload-outlined> ? ? ? Click to Upload ? ? </a-button> ? </a-upload> </template>
<script> import { message } from 'ant-design-vue'; import { UploadOutlined } from '@ant-design/icons-vue'; import { defineComponent, ref } from 'vue'; export default defineComponent({ ? components: { ? ? UploadOutlined, ? }, ? setup() { ? ? const handleChange = info => { ? ? ? if (info.file.status !== 'uploading') { ? ? ? ? console.log(info.file, info.fileList); ? ? ? } ? ? ? if (info.file.status === 'done') { ? ? ? ? message.success(`${info.file.name} file uploaded successfully`); ? ? ? } else if (info.file.status === 'error') { ? ? ? ? message.error(`${info.file.name} file upload failed.`); ? ? ? } ? ? }; ? ? const fileList = ref([]); ? ? return { ? ? ? fileList, ? ? ? headers: { ? ? ? ? authorization: 'authorization-text', ? ? ? }, ? ? ? handleChange, ? ? }; ? }, }); </script>
使用hooks函數(shù)封裝后
<template> ? <a-upload ? ? v-model:file-list="fileList" ? ? name="file" ? ? :multiple="true" ? ? action="https://www.mocky.io/v2/5cc8019d300000980a055e76" ? ? :headers="headers" ? ? @change="handleChange" ? > ? ? <a-button> ? ? ? <upload-outlined></upload-outlined> ? ? ? Click to Upload ? ? </a-button> ? </a-upload> </template>
<script> import { UploadOutlined } from '@ant-design/icons-vue'; import { defineComponent } from 'vue'; // hook import useUpload from '../hooks/useUpload'; export default defineComponent({ ? components: { ? ? UploadOutlined, ? }, ? setup() { ? ? / 上傳hooks ? ? const { fileList, headers, handleChange } = useUpload(); ? ? return { ? ? ? fileList, ? ? ? headers, ? ? ? handleChange, ? ? }; ? }, }); </script>
hooks函數(shù)
import { ref } from 'vue'; import { message } from 'ant-design-vue'; export default function useUpload() { const handleChange = (info) => { if (info.file.status !== 'uploading') { console.log(info.file, info.fileList); } if (info.file.status === 'done') { message.success(`${info.file.name} file uploaded successfully`); } else if (info.file.status === 'error') { message.error(`${info.file.name} file upload failed.`); } }; const fileList = ref([]); return { fileList, headers: { authorization: 'authorization-text', }, handleChange, }; }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue2.0 vue-source jsonp 跨域請(qǐng)求
這篇文章主要介紹了Vue2.0 vue-source jsonp 跨域請(qǐng)求,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08vue實(shí)現(xiàn)簡(jiǎn)單的MVVM框架
這篇文章給大家分享了基于vue實(shí)現(xiàn)一個(gè)簡(jiǎn)單的MVVM框架的相關(guān)內(nèi)容,有需要的朋友們可以參考學(xué)習(xí)下。2018-08-08vue中手機(jī)號(hào),郵箱正則驗(yàn)證以及60s發(fā)送驗(yàn)證碼的實(shí)例
下面小編就為大家分享一篇vue中手機(jī)號(hào),郵箱正則驗(yàn)證以及60s發(fā)送驗(yàn)證碼的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03基于vue-cli搭建多模塊且各模塊獨(dú)立打包的項(xiàng)目
這篇文章主要介紹了基于vue-cli搭建多模塊且各模塊獨(dú)立打包的項(xiàng)目,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06vue使用tracking實(shí)現(xiàn)人臉識(shí)別/人臉偵測(cè)完整代碼
作為一個(gè)AI模型,人臉識(shí)別涉及到多個(gè)技術(shù)領(lǐng)域,下面這篇文章主要給大家介紹了關(guān)于vue使用tracking實(shí)現(xiàn)人臉識(shí)別/人臉偵測(cè)的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09安裝vue-cli報(bào)錯(cuò) -4058 的解決方法
這篇文章主要介紹了安裝vue-cli報(bào)錯(cuò) -4058 的解決方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10詳解如何使用vue實(shí)現(xiàn)可視化界面設(shè)計(jì)
Vue是一款流行的前端開發(fā)框架,它的響應(yīng)式數(shù)據(jù)綁定和組件化特性使得它成為了可視化界面設(shè)計(jì)的一個(gè)理想選擇,本文將介紹如何使用Vue實(shí)現(xiàn)可視化界面設(shè)計(jì),并且演示一個(gè)基于Vue的可視化界面設(shè)計(jì)案例,需要的朋友可以參考下2023-12-12