zmc
2023-08-08 b02933d884643237f87b731da571143f41714f7a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
// 全局状态,创建在模块作用域下
 
export function useCount() {
  // 局部状态,每个组件都会创建
  const localCount = ref(1)
 
 
  return {
 
    localCount
  }
}
 
 
// 按照惯例,组合式函数名以“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 }
}