Vue3 逻辑复用 - 组合式函数

"组合式函数"(Composables) 是一个利用 Vue 的组合式 API 来封装和复用有状态逻辑的函数。

一个实现实现鼠标跟踪功能

javascript 复制代码
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const x = ref(0)
const y = ref(0)

function update(event) {
  x.value = event.pageX
  y.value = event.pageY
}

onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>

<template>Mouse position is at: {{ x }}, {{ y }}</template>

如果我们想在多个组件中复用这个相同的逻辑
可以把这个逻辑以一个组合式函数的形式提取到外部文件中:

外部文件 mouse.js

javascript 复制代码
// mouse.js
import { ref, onMounted, onUnmounted } from 'vue'

// 按照惯例,组合式函数名以"use"开头
export function useMouse() {
  // 被组合式函数封装和管理的状态
  const x = ref(0)
  const y = ref(0)

  // 组合式函数可以随时更改其状态。
  function update(event) {
    x.value = event.pageX
    y.value = event.pageY
  }

  // 一个组合式函数也可以挂靠在所属组件的生命周期上
  // 来启动和卸载副作用
  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))

  // 通过返回值暴露所管理的状态
  return { x, y }
}

引入到组件:

javascript 复制代码
<script setup>
import { useMouse } from './mouse.js'

const { x, y } = useMouse()
</script>

<template>Mouse position is at: {{ x }}, {{ y }}</template>

在,useMouse() 的功能可以在任何组件中轻易复用了。

相关推荐
葡萄城技术团队4 分钟前
SpreadJS ReportSheet 与 DataManager 实现 Token 鉴权:全流程详解与代码解析
前端
勤劳打代码4 分钟前
触类旁通 —— Flutter 与 React 对比解析
前端·flutter·react native
Glommer5 分钟前
某红书 Js 逆向思路
javascript·逆向
Mintopia5 分钟前
🧠 可解释性AIGC:Web场景下模型决策透明化的技术路径
前端·javascript·aigc
Mintopia8 分钟前
⚙️ Next.js 事务与批量操作:让异步的世界井然有序
前端·javascript·全栈
若梦plus10 分钟前
多端开发之React-Native原理浅析
前端·react native
新兵蛋子013 分钟前
基于 vue3 完成领域模型架构建设
前端
今禾15 分钟前
Git完全指南(中篇):GitHub团队协作实战
前端·git·github
Tech_Lin15 分钟前
前端工作实战:如何在vite中配置代理解决跨域问题
前端·后端