What is the Vue.js Composition API and how does it differ from the Options API? I'll explain it here!
25. August 2024
The Composition API was introduced with Vue 3 to provide developers with more flexibility and better logical structuring of code. Instead of dividing code by options (such as data
, methods
, computed
, etc.), the Composition API allows for organizing logical units independently of these options.
The Options API organizes code by options (e.g., data
, methods
, computed
). This is easy to understand but can become cumbersome with complex components.
The Composition API, on the other hand, groups related logic in setup
functions and can also be moved to external functions.
<script>
export default {
data() {
return {
counter: 0
};
},
methods: {
increment() {
this.counter++;
}
},
computed: {
doubleCounter() {
return this.counter * 2;
}
}
};
</script>
<script lang="ts" setup>
import { ref, computed } from 'vue';
const counter = ref(0);
function increment() {
counter.value++;
}
const doubleCounter = computed(() => counter.value * 2);
</script>
In the Options API, methods, data, and computed properties are separated by their function. In the Composition API, however, logic is consolidated, leading to better clarity and modularity, especially in larger components.
<script>
export default {
data() {
return {
message: "Hello, world!",
count: 0
};
},
methods: {
incrementCount() {
this.count++;
}
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
};
</script>
<script lang="ts" setup>
import { ref, computed } from 'vue';
const message = ref("Hello, world!");
const count = ref(0);
function incrementCount() {
count.value++;
}
const reversedMessage = computed(() => message.value.split('').reverse().join(''));
</script>
In the Options API example, data, methods, and computed are clearly separated. In the Composition API example, the logic for the counter and the message is within the setup block, providing better clarity and easier reuse of logic.