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() 的功能可以在任何组件中轻易复用了。

相关推荐
你真的可爱呀1 天前
uniapp+vue3项目中的常见报错情况以及解决方法
前端·vue.js·uni-app
差点GDP1 天前
模拟请求测试 Fake Rest API Test
前端·网络·json
酒尘&1 天前
Hook学习-上篇
前端·学习·react.js·前端框架·react
houyhea1 天前
从香港竹脚手架到前端脚手架:那些"借来"的发展智慧与安全警示
前端
哈哈~haha1 天前
Step 14: Custom CSS and Theme Colors 自定义CSS类
前端·css·ui5
Ndmzi1 天前
Matlab编程技巧:自定义Simulink菜单(理解补充)
前端·javascript·python
勇气要爆发1 天前
物种起源—JavaScript原型链详解
开发语言·javascript·原型模式
我命由我123451 天前
VSCode - VSCode 修改文件树缩进
前端·ide·vscode·前端框架·编辑器·html·js
SoaringHeart1 天前
Flutter组件封装:验证码倒计时按钮 TimerButton
前端·flutter
San30.1 天前
深入理解 JavaScript OOP:从一个「就地编辑组件」看清封装、状态与原型链
开发语言·前端·javascript·ecmascript