Vue3自定义hook函数

一、hook的概念


  1. 什么是hook?

    • 本质是一个函数,把setup函数中使用的Composition API进行了封装。
    • 类似于vue2.x中的mixin。
  2. 自定义hook的优势

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

二、hook的使用


在这里插入图片描述

App组件

<template>
	<button @click="isShowDemo = !isShowDemo">切换隐藏/显示</button>
	<hr>
	<Demo v-if="isShowDemo"/>
	<hr>
	<Test/>
</template>

<script>
	import {ref} from 'vue'
	import Demo from './components/Demo.vue'
	import Test from './components/Test.vue'
	export default {
		name: 'App',
		components:{Demo,Test},
		setup() {
			let isShowDemo = ref(true)
			return {isShowDemo}
		}
	}
</script>

Demo组件

<template>
	<h2>我的是Demo组件</h2>
	<h3>当前求和为:{{sum}}</h3>
	<button @click="sum++">点我+1</button>
	<h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
</template>

<script>
	import {ref} from 'vue'
	import usePoint from '../hooks/usePoint'
	export default {
		name: 'Demo',
		setup(){
			let sum = ref(0)
			let point = usePoint()
			return {sum,point}
		}
	}
</script>

Test组价

<template>
	<h2>我是Test组件</h2>
	<h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
</template>

<script>
	import usePoint from '../hooks/usePoint'
	export default {
		name:'Test',
		setup(){
			const point = usePoint()
			return {point}
		}
	}
</script>

Hook函数

import { reactive, onMounted, onBeforeUnmount } from 'vue'
export default function () {
	//实现鼠标“打点”相关的数据
	let point = reactive({
		x: 0,y: 0
	})

	//实现鼠标“打点”相关的方法
	function savePoint(event) {
		point.x = event.pageX
		point.y = event.pageY
		console.log(event.pageX, event.pageY)
	}

	//实现鼠标“打点”相关的生命周期钩子
	onMounted(() => {
		window.addEventListener('click', savePoint)
	})

	onBeforeUnmount(() => {
		window.removeEventListener('click', savePoint)
	})

	return point
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值