Currently Available: Need a skilled Software Developer for your next project?
Categories
Software Architecture Vue

Inline Composables in Vue

Inline composables offer a way to refactor components without creating multiple files. The idea is to organize related functionality into units within the same component file.

Example: Refactoring a Component

Consider a dashboard component:

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

// Authentication logic
const user = ref(null)
const isAuthenticated = computed(() => !!user.value)
const login = async (credentials) => { /* ... */ }
const logout = () => { /* ... */ }

// Project data management
const projects = ref([])
const loading = ref(false)
const error = ref(null)
const fetchProjects = async () => { /* ... */ }

// Task management
const tasks = ref([])
const addTask = (task) => { /* ... */ }
const completeTask = (taskId) => { /* ... */ }

// UI state
const activeTab = ref('overview')
const isModalOpen = ref(false)

onMounted(() => {
  fetchProjects()
})
</script>

<template>
  <!-- Template code -->
</template>

Refactored with Inline Composables

Here's the component refactored using inline composables:

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

const useAuth = () => {
  const user = ref(null)
  const isAuthenticated = computed(() => !!user.value)
  const login = async (credentials) => { /* ... */ }
  const logout = () => { /* ... */ }
  return { user, isAuthenticated, login, logout }
}

const useProjects = () => {
  const projects = ref([])
  const loading = ref(false)
  const error = ref(null)
  const fetchProjects = async () => { /* ... */ }
  return { projects, loading, error, fetchProjects }
}

const useTasks = () => {
  const tasks = ref([])
  const addTask = (task) => { /* ... */ }
  const completeTask = (taskId) => { /* ... */ }
  return { tasks, addTask, completeTask }
}

const useUIState = () => {
  const activeTab = ref('overview')
  const isModalOpen = ref(false)
  return { activeTab, isModalOpen }
}

const { user, isAuthenticated, login, logout } = useAuth()
const { projects, loading, error, fetchProjects } = useProjects()
const { tasks, addTask, completeTask } = useTasks()
const { activeTab, isModalOpen } = useUIState()

onMounted(() => {
  fetchProjects()
})
</script>

<template>
  <!-- Template remains unchanged -->
</template>
What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Subscribe to my newsletter

Get new posts when I publish them.

I respect your privacy. Unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *