Questions
What is the Composition API and how does it compare to the Options API?
The Scenario
You are a frontend engineer at a social media company. You are working on a new component that is very large and complex.
You are finding it difficult to organize the component’s code using the Options API, because the code for a single feature is spread out across multiple options (e.g., data, methods, computed).
The Challenge
Explain what the Composition API is in Vue and how it can be used to solve this problem. What are the key benefits of using the Composition API over the Options API?
A junior engineer might not be aware of the Composition API. They might try to solve this problem by breaking the component down into smaller components, which would be a good start, but it would not solve the underlying problem of code organization.
A senior engineer would know that the Composition API is the perfect tool for this job. They would be able to explain what the Composition API is and how to use it to organize the code for a large and complex component.
Step 1: Understand the Key Differences
| Feature | Options API | Composition API |
|---|---|---|
| Organization | Code is organized by option (e.g., data, methods, computed). | Code is organized by logical concern (e.g., a feature). |
| Reusability | Code can be reused with mixins, but this can lead to name collisions and implicit dependencies. | Code can be reused with composable functions, which are more explicit and easier to reason about. |
| TypeScript | Limited TypeScript support. | Full TypeScript support. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use the Composition API. This is because we are working on a large and complex component, and the Composition API will allow us to organize the code by logical concern, which will make it more readable and maintainable.
Step 3: Code Examples
Here’s how we can rewrite our component using the Composition API:
Options API:
export default {
data() {
return {
// ...
};
},
methods: {
// ...
},
computed: {
// ...
}
};Composition API:
import { ref, computed } from 'vue';
export default {
setup() {
const myVar = ref(0);
const myComputed = computed(() => {
// ...
});
function myMethod() {
// ...
}
return {
myVar,
myComputed,
myMethod
};
}
};As you can see, the Composition API allows us to group all the code for a single feature together in one place.
Practice Question
You want to share a piece of reactive state between multiple components. Which of the following would be the most appropriate?