Extraction and reuse logic in the Vue3 Composition API

The Vue3 Composition API allows better organization of code in large projects.However, as you switch to a single setup method using several different option properties, the problem faced by many developers is...

Would this be more confusing, because everything is in one way

At first glance it may be easy, but it actually takes a little time to write reusable modular code.

Let's see how we can do this.

problem

The Options API for Vue.js 2.x is a very intuitive way to separate code

export default {
  data () {
    return {
      articles: [],
      searchParameters: []
    }
  },
  mounted () {
    this.articles = ArticlesAPI.loadArticles()
  },
  methods: {
    searchArticles (id) {
      return this.articles.filter(() => {
        // Some search codes
      })
    }
  }
}
Copy Code

The problem is that if you have hundreds of lines of code in a component, you must add code for a single feature, such as search, in multiple parts of data, methods, computed, and so on.

This means that code for just one feature can be spread out over hundreds of lines and in several different locations, making it difficult to read or debug.

This is just one example in the Vue Composition API RFC that shows how code is now organized by function.

Now, this is the equivalent code for using the new Composition API.

import { ref, onMounted } from 'vue'

export default {
  setup () {
    const articles = ref([])
    const searchParameters = ref([])

    onMounted(() => {
      this.articles = ArticlesAPI.loadArticles()
    })

    const searchArticles = (id) => {
      return articles.filter(() => {
        // Some search codes
      })
    }

    return {
      articles,
      searchParameters,
      searchArticles
    }
  }
}
Copy Code

Now, to solve the previous organization issues, let's look at a good way to extract logic.

Extraction logic

Our ultimate goal is to extract each feature into its own method.So if we want to debug it, all the code is in one place.

This is very simple, but finally we have to remember that if we want to be able to access the data in the template, we still have to use our setup method to return the data.

Let's create a new method, useSearchArticles, and let it return everything we return in the setup method.

const useSearchArticles = () => {
  const articles = ref([])
  const searchParameters = ref([])

  onMounted(() => {
    this.articles = ArticlesAPI.loadArticles()
  })

  const searchArticles = (id) => {
    return articles.filter(() => {
      // Some search codes
    })
  }

  return {
    articles,
    searchParameters,
    searchArticles
  }
}
Copy Code

Now, in our setup method, we can access the properties by calling our method.And, of course, we must remember to return them from the set up method.

export default {
  setup () {
    const { articles, searchParameters, searchArticles } = useSearchArticles()

    return {
      articles,
      searchParameters,
      searchArticles
    }
  }
}
Copy Code

Accessing component properties in extracted logic

Another new change in the Composition API is the change referenced by this, which means we can no longer use prop, attributes, or events in the same way.

In short, we will have to use two parameters of the setup method to access the props, attribute, slot, or emit methods.If we only use the setup method, a fast virtual component might be.

export default {
  setup (props, context) {

    onMounted(() => {
      console.log(props)
      context.emit('event', 'payload')
    })
  }
}
Copy Code

But now we're going to extract our logic, and we're going to accept parameters for our logical wrapper method as well.In this way, we can pass our props and context properties from the setup method, and the logical code can access them.

const checkProps = (props, context) => {
  onMounted(() => {
    console.log(props)
    context.emit('event', 'payload')
  })
}
export default {
  setup (props, context) {
    checkProps(props, context)
  }
}
Copy Code

Reuse logic

Finally, if we want to write some logic that we want to be able to use in multiple components, we can extract the logic into our own files and import it into our components.

Then we can call the method as before.Suppose we move our useSearchArticles method to a file named use-search-articles-logic.js, as shown below

import { ref, onMounted } from 'vue'
export function useSearchArticles () {
  const articles = ref([])
  const searchParameters = ref([])

  onMounted(() => {
    this.articles = ArticlesAPI.loadArticles()
  })

  const searchArticles = (id) => {
    return articles.filter(() => {
      // Some search codes
    })
  }

  return {
    articles,
    searchParameters,
    searchArticles
  }
}
Copy Code

With this new file, our original components will look like this

import { useSearchArticles } from './logic/use-search-articles-logic'
export default {
  setup (props,) {
    const { articles, searchParameters, searchArticles } = useSearchArticles()

    return {
      articles,
      searchParameters,
      searchArticles
    }
  }
}
Copy Code

Last

Hopefully this article will help you better understand how the Composition API will change the way we code.

However, as always, the organization of a project depends on the developer's willingness to design well-designed component code and create reusable logic.

Remember, our goal is to improve readability, and in Vue, the Composition API is a good way to do that.

Original: learnvue.co/2020/03/ext...

Author: Matt Maribojoc

The Public Number will be released two or three days in priority, so keep an eye on it!And big gift packs!

Keywords: Vue Attribute

Added by uatec on Thu, 23 Apr 2020 04:06:24 +0300