Search⌘ K

Composable Files

Explore how to create and use composable files in Nuxt 3's Composition API to group related logic, improve code reusability, and organize your application. Learn to extract code into standalone JavaScript files and how to access them across pages and components.

Using the Composition API, we can address some of the limitations of the Options API:

  • Code can be written in a more JavaScript-like way.

  • Related code can be grouped more closely for organization.

However, we have not covered how it makes our code more reusable. The Composition API aims to resolve this, along with improving our organisation even further.

Composable files

Let's look at this example:

Javascript (babel-node)
<script setup>
// user
const user = ref({})
function getUser() {
user.value = { name: "Bob" };
}
onMounted(getUser)
// products
const products = ref([]);
function getProducts() {
products.value.push("blue shirt");
}
onMounted(getProducts);
// basket
const basket = ref([]);
const showBasket = computed(() => (basket.length > 0 ? true : false));
function updateBasket(item) {
basket.value.push(item);
}
</script>

Here is an explanation of the above code:

  • Line 4: We create a user const to hold the user object.

  • Lines 5–7: ...