Vue3 composition API style tip

I have a couple of new projects on the go, and I really want to try out the composition API for Vue3. I’ve seen a few examples on-line, and they emphasise using the setup method to create refs and computeds using the composition API functions. And they all end up with all that code in one giant setup function. At which point, I imagine that scaled-up to a full application, and find myself thinking “Surely, you can’t be serious?”

Surely you can't be serious GIF from the movie Airplane

The Vue3 style guide doesn’t offer any suggestions, and searching online for composition API style guide or tips wasn’t very fruitful.

However, it turns out that the Vue3 docs do directly address this concern:

We could do the same for other logical concerns but you might be already asking the question – Isn’t this just moving the code to the setup option and making it extremely big? Well, that’s true. That’s why before moving on with the other responsibilities, we will first extract the above code into a standalone composition function.

source

The recommendation goes on to suggest creating a composables directory, from which we can import these logical-features into a component’s setup function:

// src/components/UserRepositories.vue
import useUserRepositories from '@/composables/useUserRepositories'
import { toRefs } from 'vue'

export default {
  components: { RepositoriesFilters, RepositoriesSortBy, RepositoriesList },
  props: {
    ...
  },
  setup (props) {
    const { user } = toRefs(props)

    const { repositories, getUserRepositories } = useUserRepositories(user)

I think there will be much more to say on creating good patterbs for structuring composition-API Vue3 components, but for now I just wanted to add some search-juice for this suggestion for a style-guide for Vue3 components using the composition API.

 newer · index · older