vue3+ts 自定义hook函数

  • Post author:
  • Post category:vue


首先在src下建立一个文件夹,命名:userhookhandle

在文件夹下面建立usermousehandles.ts

import { onBeforeUnmount, onMounted, ref } from ‘vue’

export default function () {

const x = ref(1)

const y = ref(1)

const clickhandler = (event:MouseEvent) => {

x.value = event.pageX

y.value = event.pageY

}

onMounted(() => {

window.addEventListener(‘click’, clickhandler)

})

onBeforeUnmount(() => {

window.removeEventListener(‘click’, clickhandler)

// 卸载钩子

})

return {

x,

y

}

}

主页APP文件夹

<template>

<div>

<h2>坐标轴{

{x}}</h2>

<h2>坐标轴{

{y}}</h2>

</div>

</template>

<script lang=”ts”>

import { defineComponent } from ‘vue’

import usermousehandle from ‘./userhookhandle/usermousehandle’

export default defineComponent({

setup () {

const { x, y } = usermousehandle()

return {

x,

y

}

}

})

</script>