How to implement logic reuse with Vue3 composition API

How to implement logic reuse with Vue3 composition API

Composition API implements logic reuse steps:

  1. Extract the logic code into a function, the function command convention is useXXX format (this is the same as React Hooks)
  2. Reference function useXXX in setup

For example, define a method to get the current mouse position

The first one is to use the useMousePosition defined by ref directly:

This way, both exports and imports can be destructured at will

// useMousePosition.js
import { ref, onMounted, onUnmounted } from 'vue'

// 1. Define a function, extract logic, and name it useXXX
function useMousePosition() {
  // Use ref to define const x = ref(0)
  const y = ref(0)

  function update(e) {
    console.log(x.value, y.value);

    x.value = e.pageX
    y.value = e.pageY
  }

  onMounted(() => {
    console.log('Start listening for mouse movement events');
    window.addEventListener('mousemove', update)
  })

  onUnmounted(() => {
    console.log('Remove mouse scroll event monitoring');
    window.removeEventListener('mousemove', update)
  })
  return {
    x, 
    y
  }
}

 
// Export this function export default useMousePosition
<!-- This method can be called in any component-->

<template>
  <p>mouse position: {{x}}, {{y}}</p>
</template>

<script>
import useMousePosition from './useMousePosition'
export default {
  name: 'MousePosition', 
  setup() {
    // useMousePosition uses ref to define variables, which can be deconstructed const { x, y } = useMousePosition()
    console.log(x, y)
    return {
      x, y
    }
  }
}
</script>

The second method is to use reactive to define the mouse coordinate object.

This export method cannot be destructured when imported into a component.

import { onMounted, onUnmounted, reactive } from 'vue'

export function useMousePosition2() {
  // Use reactive to define const mouse = reactive({
    x: 0, 
    y: 0
  })

  function update(e) {
    mouse.x = e.pageX
    mouse.y = e.pageY
  }

  onMounted(() => {
    console.log('Start listening for mouse movement events');
    window.addEventListener('mousemove', update)
  })

  onUnmounted(() => {
    console.log('Remove mouse scroll event monitoring');
    window.removeEventListener('mousemove', update)
  })

  return {
    mouse
  }
}
<template>
  <!-- Use object method to display information -->
  <p>mouse position2: {{mouse.x}}, {{mouse.y}}</p>
</template>
<script>
import { useMousePosition2 } from './useMousePosition'
export default {
  name: 'MousePosition', 
  setup() {
    // useMousePosition2 is defined using reactive, so deconstruction is not possible const { mouse } = useMousePosition2()
    return {
      mouse
    }
  }
}
</script>

The third method is to use toRefs

Using this method, you can deconstruct reactive objects into ref objects.

export function useMousePosition3() {
  // Use reactive to define const mouse = reactive({
    x: 0, 
    y: 0
  })

  function update(e) {
    mouse.x = e.pageX
    mouse.y = e.pageY
  }

  onMounted(() => {
    console.log('Start listening for mouse movement events');
    window.addEventListener('mousemove', update)
  })

  onUnmounted(() => {
    console.log('Remove mouse scroll event monitoring');
    window.removeEventListener('mousemove', update)
  })
  
  // Here, use toRefs to deconstruct into ref object return toRefs(mouse)
}
<template>
  <p>mouse position: {{x}}, {{y}}</p>
</template>

<script>
import { useMousePosition3 } from './useMousePosition'
export default {
  name: 'MousePosition', 
  setup() {
    // Use reactive to define the mouse coordinate object, and then deconstruct it into a ref object through toRefs const { x, y } = useMousePosition()
    console.log(x, y)
    return {
      x, y
    }
  }
}
</script>

All three methods can be implemented, but when we generally use them, we will return the ref object, so it is recommended to use the first and third methods and try not to use the second method.

This is the end of this article about how to implement logic reuse with Vue3 composition API. For more information about Vue3 composition API logic reuse, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Practice of using Vite2+Vue3 to render Markdown documents
  • Vue3 navigation bar component encapsulation implementation method
  • Vue3 Vue Event Handling Guide
  • In-depth explanation of the style feature in Vue3 single-file components
  • vue3.0+echarts realizes three-dimensional column chart
  • This article will show you how to use Vue 3.0 responsive
  • Detailed explanation of the underlying principle of defineCustomElement added in vue3.2
  • Vue3 + TypeScript Development Summary
  • Vue3+TypeScript implements a complete example of a recursive menu component
  • Vue3 implements a todo-list
  • Vue3+script setup+ts+Vite+Volar project
  • Vue3 realizes the image magnifying glass effect
  • Implementation of vue3.0+vant3.0 rapid project construction
  • Vue3 Documentation Quick Start

<<:  Problems encountered when installing mysql8.0.15 winx64 on Win10 and connecting to the server

>>:  Tutorial analysis of quick installation of mysql5.7 based on centos7

Recommend

Bundling non-JavaScript static resources details

Table of contents 1. Custom import in packaging t...

A brief discussion on the definition and precautions of H tags

Judging from the results, there is no fixed patte...

Install MySQL 5.7.17 in win10 system

Operating system win10 MySQL is the 64-bit zip de...

js realizes packaging multiple pictures into zip

Table of contents 1. Import files 2. HTML page 3....

MySQL Series 8 MySQL Server Variables

Tutorial Series MySQL series: Basic concepts of M...

Mysql 5.6 "implicit conversion" causes index failure and inaccurate data

background When performing a SQL query, I tried t...

Several important MySQL variables

There are many MySQL variables, some of which are...

Implementing user registration function with js

This article example shares the specific code of ...

Use vertical-align to align input and img

Putting input and img on the same line, the img ta...

Vue project implements file download progress bar function

There are two common ways to download files in da...

centos7.2 offline installation mysql5.7.18.tar.gz

Because of network isolation, MySQL cannot be ins...

Sample code for implementing mysql master-slave replication in docker

Table of contents 1. Overview 1. Principle 2. Imp...

How to use nodejs to write a data table entity class generation tool for C#

Although Microsoft provides T4 templates, I find ...

Nginx reverse proxy forwards port 80 requests to 8080

Let's first understand a wave of concepts, wh...

Summary of common commands in Dockerfile

Syntax composition: 1 Annotation information 2 Co...