vue3 组合式函数 Composition API

parent.vue

<template>Mouse position is at: {
   
   { x }}, {
   
   { y }}</template>
<script setup>
// 这个是官网的实例, 在 setup 模式中 用来代替 vue2 中的 mixins 
import {
      
       useMouse } from './mouse.js'

const {
      
       x, y } = useMouse();

</script>

<style lang="less" scoped>

</style>

mouse.js

// 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 }
}

猜你喜欢

转载自blog.csdn.net/qq_38946996/article/details/128079310
今日推荐