chenhuiYj / chenhuiYj/note

vue3 - 自定义hook

Open
#45 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
HTML
Stars
6
Forks
0
PR merge metrics
No merged PRs in 30d

Description

这一点跟 Composition API 的复用如出一辙。比如实现一个鼠标点击,输出页面坐标的 hook。

useMouse.js

import { ref, onMounted, onUnmounted } from "vue";

export default function useMouse(){
  let pointX=ref(0)
  let pointY=ref(0)

  //这里需要使用函数,如果只使用()=>{},无法 remove 事件,因为两个()=>{}不是同一个函数
  function getMousePoint(e){
	  	pointX.value = e.pageX;
    	pointY.value = e.pageY;

  }
  onMounted(()=>{
    window.addEventListener('click',getMousePoint)
  })

	
  onUnmounted(()=>{
window.removeEventListener("click", getMousePoint);
})

  return {pointX, pointY}
}

App.vue

<script setup>
import useMouse from './useMouse'

let {pointX,pointY}=useMouse()
</script>

<template>
  <p>x:{{pointX}}</p>
  <p>y:{{pointY}}</p>
</template>

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the useMouse.js and App.vue examples in the issue, then review how the Vue 3 Composition API lifecycle hooks are presented. Done means the note clearly explains the reusable mouse-coordinate hook and its component usage.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation, frontend
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.