Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Composable — Encapsulating Reusable Logic

Composable — Encapsulating Reusable Logic

In this chapter you will learn the best practice of Vue 3 — using composable functions (Composable) to encapsulate reusable logic, making the code cleaner and easier to maintain.


What Is a Composable?

As features grow, the JS logic inside components gets longer. Both the home page and the detail page need to load article data, so the code gets duplicated.

A Composable is a function that extracts reusable logic into an independent JS function, which can be called wherever a component needs it.

Its essence is simply an ordinary function that returns reactive data and methods.


Why Do We Need a Composable?

Compare the code structure before and after the change:

Without Composable (before) With Composable (after)
Each component writes its own fetch logic One usePosts() reused everywhere
Data loading and UI logic are mixed together Data logic is independent; components only care about the UI
Changing one piece of logic requires editing multiple files Change one place, all components update in sync
Component code expands rapidly with business growth Component code has a single responsibility and a manageable size

If you have used Vue 2's Mixins, a Composable can be understood as a clearer and safer alternative — it has no naming conflicts and transparent data sources.


Naming Conventions and Agreements

Convention Description Example
Starts with use Instantly recognizable as a Composable usePosts, useDarkMode
Place in the composables/ directory Easy to find and maintain src/composables/usePosts.js
Return reactive data Return ref or reactive so callers stay reactive return { articles, isLoading }
One function does one thing Single responsibility, easy to compose usePosts only handles data, useDarkMode only handles the theme

usePosts — Encapsulating Article Data Logic

This Composable is responsible for: loading data + category filtering + search filtering.

Example

// File path: src/composables/usePosts.js

import

{

ref

,

computed

,

onMounted

}

from

'vue'

export

function

usePosts

(

)

{

 

const

articles

=

ref

(

[

]

)

         

// All article data

 

const

isLoading

=

ref

(

true

)

       

// Loading state

 

const

error

=

ref

(

null

)

           

// Error message

 

const

activeCategory

=

ref

(

'All'

)

// Currently selected category

 

const

keyword

=

ref

(

''

)

           

// Search keyword

 

// Extract all categories (deduplicated)

 

const

categories

=

computed

(

(

)

=>

{

   

const

cats

=

articles.

value

.

map

(

a

=>

a.

category

)

   

return

[

'All'

,

...

new

Set

(

cats

)

]

 

}

)

 

// Filtered articles: first by category, then by keyword

 

const

filteredArticles

=

computed

(

(

)

=>

{

    let result

=

articles.

value

   

// Filter by category

   

if

(

activeCategory.

value

!==

'All'

)

{

      result

=

result.

filter

(

a

=>

a.

category

===

activeCategory.

value

)

   

}

   

// Filter by keyword (match title or summary)

   

if

(

keyword.

value

.

trim

(

)

)

{

     

const

kw

=

keyword.

value

.

trim

(

)

.

toLowerCase

(

)

      result

=

result.

filter

(

a

=>

        a.

title

.

toLowerCase

(

)

.

includes

(

kw

)

||

        a.

summary

.

toLowerCase

(

)

.

includes

(

kw

)

     

)

   

}

   

return

result

 

}

)

 

// Find a single article by ID

 

function

getArticleById

(

id

)

{

   

return

articles.

value

.

find

(

a

=>

a.

id

===

id

)

 

}

 

// Switch category

 

function

setCategory

(

cat

)

{

    activeCategory.

value

=

cat

 

}

 

// Load data

  async

function

fetchPosts

(

)

{

    isLoading.

value

=

true

    error.

value

=

null

   

try

{

     

const

res

=

await fetch

(

'/posts.json'

)

     

if

(

!

res.

ok

)

throw

new

Error

(

`HTTP $

{

res.

status

}

`

)

      articles.

value

=

await res.

json

(

)

   

}

catch

(

err

)

{

      error.

value

=

err.

message

   

}

finally

{

      isLoading.

value

=

false

   

}

 

}

 

// Auto-load when the component mounts

  onMounted

(

(

)

=>

{

    fetchPosts

(

)

 

}

)

 

// Return data and methods for the component to use

 

return

{

    articles

,

    isLoading

,

    error

,

    activeCategory

,

    keyword

,

    categories

,

    filteredArticles

,

    getArticleById

,

    setCategory

,

    fetchPosts

 

}

}

Now the home page component becomes very concise; you only need to call usePosts:

Example

The detail page can also reuse usePosts without rewriting the fetch. Note that you need to import separately from Vue: computed:

Example

Note: If the user accesses the detail page URL directly (e.g., refreshing the page), usePosts will re-fetch the data. Because the home page and detail page are different component instances, each call to usePosts executes the fetch inside onMounted, and the data is not shared. If you need to share the same data across pages, you can lift the state to a Pinia store, or call it once in a top-level component and pass it down via provide / inject.


useDarkMode — Switch Dark Mode with One Line of Code

The core idea of dark mode: add a class on the html tag, then control colors with CSS variables.

The user's choice is stored in localStorage and automatically restored on the next visit.

Example

// File path: src/composables/useDarkMode.js

import

{

ref

,

watchEffect

}

from

'vue'

export

function

useDarkMode

(

)

{

 

// Read the user's previous setting from localStorage (default to light if none)

 

const

saved

=

localStorage.

getItem

(

'blog-theme'

)

 

const

isDark

=

ref

(

saved

===

'dark'

)

 

// Apply theme to the DOM

 

function

applyTheme

(

dark

)

{

   

if

(

dark

)

{

      document.

documentElement

.

classList

.

add

(

'dark'

)

      localStorage.

setItem

(

'blog-theme'

,

'dark'

)

   

}

else

{

      document.

documentElement

.

classList

.

remove

(

'dark'

)

      localStorage.

setItem

(

'blog-theme'

,

'light'

)

   

}

 

}

 

// watchEffect runs once immediately to apply the initial theme

 

// After that, whenever isDark changes, it syncs to the DOM automatically

  watchEffect

(

(

)

=>

{

    applyTheme

(

isDark.

value

)

 

}

)

 

// Toggle dark mode

 

function

toggleDark

(

)

{

    isDark.

value

=

!

isDark.

value

 

}

 

return

{

isDark

,

toggleDark

}

}

In NavBar, you only need two lines:

Example

Combined with global CSS variables to switch themes

Example

/* File path: src/assets/main.css */

/* Light mode (default) */

:root

{

  --bg-primary

:

   

#f5f5f5

;

  --bg-card

:

     

#ffffff

;

  --text-primary

:

 

#333333

;

  --text-secondary

:

#666666

;

  --border-color

:

 

#eeeeee

;

}

/* Dark mode (takes effect when the html tag has the .dark class) */

html

.dark

{

  --bg-primary

:

   

#1a1a2e

;

  --bg-card

:

     

#16213e

;

  --text-primary

:

 

#e0e0e0

;

  --text-secondary

:

#a0a0a0

;

  --border-color

:

 

#2a2a4a

;

}

/* Components reference these variables; switching themes requires no changes to any component code */

body

{

 

background

:

var

(

--bg-primary

)

;

 

color

:

var

(

--text-primary

)

;

}

.card

{

 

background

:

var

(

--bg-card

)

;

 

border

:

1px

solid

var

(

--border-color

)

;

}

At this point, clicking the toggle button switches the entire site's colors instantly, and your choice is remembered after refreshing.


Comparison with Vue 2 Mixin

Feature Mixin (Vue2) Composable (Vue3)
Data Source Opaque; you don't know where the properties come from Clearly obtained by destructuring from return; the source is obvious
Naming Conflicts Same-named properties from multiple Mixins overwrite each other You decide the variable names; no conflicts
Type Inference Poor TypeScript support Native TypeScript support with automatic type inference
Logic Organization Organized by option (data/methods/computed) Organized by feature; one composable per file
Logic Reuse Mixins are hard to compose and easily create implicit dependencies Composables can call each other; flexible composition