Reputation: 828
I'm trying to figure out the need for the 'new' Vue Composition API.
Say we have the following component, from their basic example:
<template>
<button @click="increment">
Count is: {{ state.count }}, double is: {{ state.double }}
</button>
</template>
<script>
import { reactive, computed } from '@vue/composition-api'
export default {
setup () {
const state = reactive({
count: 0,
double: computed(() => state.count * 2),
})
function increment () {
state.count++
}
return {
state,
increment,
}
},
}
</script>
We could also write this 'composition style' using plain JavaScript, and make it available via the data
option:
<template>
<button @click="increment">
Count is: {{ state.count }}, double is: {{ state.double }}
</button>
</template>
<script>
export default {
data () {
const state = {
count: 0,
get double () {
return this.count * 2
},
}
function increment () {
state.count++
}
return {
state,
increment,
}
},
}
</script>
Is there any functional difference between these two options? What are the advantages of the Composition API?
Upvotes: 2
Views: 497
Reputation: 828
Quoted from @linusborg in the Vue Discord server:
The goal of the composition API, as indicated by its name, is to make composition easier and better - which was previously done with mixins. It aims to do so by decoupling logic from this and the Options object, and allowing us to extract functionality in simple Javascript functions that we then can compose in setup.
That kind of composition has a bunch of benefits over the Vue 2 mixins approach, i.e. easy to type in TS, easy to see where stuff comes from and which part of the code relies on what, etc. So the primary focus is to come up with better composition patterns and get rid of the problems mixins have.
Now, what you show in your code example would allow for that composition well, but only to a certain extent:
function reusableState () {
const state = {
count: 0,
get double () {
return this.count * 2
},
}
function increment () {
state.count++
}
return {
state,
increment,
}
}
export default {
data () {
return reusableState()
},
}
But this doesn't take into account a bunch of other features:
So if you actually have a piece of logic that you want to make reusable/composable, but it relies on one of these features, you can't really extract it into such a function.
That's basically where the composition API features come in - computed(), ref(), onMounted() etc.
You can read a much more in-depth exploration of the design and benefits of the composition API here: https://vue-composition-api-rfc.netlify.com/
Upvotes: 3