Composables
Two components that count clicks end up repeating the same ref and the same
increment function. The logic is identical; only the markup differs. Copying it
means fixing every bug twice.
A composable is a function that holds that logic and returns reactive state.
It uses the Composition API the same way a component's <script setup> does:
<script setup>
import { ref } from 'vue';
function useCounter() {
const count = ref(0);
function increment() {
count.value += 1;
}
return { count, increment };
}
const { count, increment } = useCounter();
</script>
Call it from any component and each call gets its own independent state, because
the ref is created inside the function. The name starts with use, the
convention that marks a composable.
The Test mounts your component and clicks the button. It checks that the count
rose, which only happens if the composable returned a reactive ref. The
starter returns a plain number, so the click changes nothing and the Test fails.
Return reactive state from the composable in App.vue.
Challenge
The counter's logic is trapped in the component. Export an App component from
App.vue that defines a useCounter composable returning a reactive count
and an increment, then renders the count on a button that calls increment.
The Test mounts your component, clicks the button, and checks the count rose.
The starter returns a plain number, so the click changes nothing and the Test
fails. Return a ref from the composable.