For those of you who don’t know much about Vue3.0, when you look at the Composition API, you may feel a bit confused and confused. What is this? What did he do? What kind of responsibilities did he undertake?

Let’s take a look at the Vue3.0 Composition API in terms everyone can understand.

What

First of all, what do these words mean?

-Leonard: You got a Composition

API: Application Programming Interface (API) : Predefined functions used for interaction between systems, components, and functions.

What does it mean to speak human language in Vue3.0?

Chinese name: composition function

“Composition API takes functions as the carrier, extracts business-related logical codes together and packages them as a whole to provide corresponding capabilities.”

It can be understood that it is a solution for us to organize code and solve logic reuse.

Why

So why does Vue3.0 use functions as a carrier to extract business-related code together?

Let’s take a look at the current Vue2. X code organization:

export default {
  props: {
    ……
  },
  data() {
    return {
        ……
    };
  },
  watch: {
    ……
  },
  computed: {... } the methods: {... }Copy the code

To implement a function in a component, you may have the following code blocks:

  • Receive parameters in props
  • Define variables in data
  • Listen for changes in Watch
  • Define the computed properties that need to be used in computed
  • Define event response methods in Methods

After writing code this way, what happens if someone else looks at the code?

If you need to find the logic of a function, you need to in this component, constantly scrolling page to view the code of each module, if the code logic is very complex, jump to jump, look really really call a uncomfortable ah!

This is the current organization code for Vue2. X, called the Options API, as shown below (just pay attention to the location of the color blocks) :

The same color area in the figure represents the same functional module. Here, it gives the impression that the whole component code is messy, and the functional code blocks appear interlaced with each other, and the colors are dazzling.

We can use Mixins, HOC, Renderless Components to get around this problem.

You are right ! These can solve this problem to some extent, but they all have some problems more or less:

  • The source of the data in the template is unclear. For example, when multiple mixins are used in a component, it can be difficult to tell from the template which mixin a property comes from. HOC has a similar problem.

  • Namespace conflict. There is no guarantee that mixins developed by different developers won’t use exactly the same properties or method names. HOC has a similar problem with the injected props.

  • Performance. Both HOC and Renderless Components require additional component instances to be nested to encapsulate logic, resulting in unnecessary performance overhead.

In addition, integrating Vue2. X’s existing APIS with Typescript does present some challenges, mainly because Vue relies on this context to throw attributes, and this has a lot of magic in Vue components compared to simple JavaScript (e.g. This in a function defined in the methods property refers to a component instance, not a methods object.

In addition to these reasons, the Composition API has two advantages:

  • Type inference: Function-based apis are naturally friendly to type inference, because TS has complete support for function parameters, return values, and generics.

  • Package size: Function-based apis Each function can be introduced separately as named ES export, making them tree-shaker-friendly. Also, because all function names and variable names inside the setup function body can be compressed, you have better compression efficiency.

The Composition API is based on trade-offs.

Where

Having said that, where does the Composition API go?

Remember that Composition apis are a solution for composing and reusing code logic, not a solution for replacing components. In other words, it does not matter how components are divided as they were.

However, the organization of code within components, and the reuse of code between components, are closely related to Composition apis, such as the following:

listenMouse.js

import { ref, onMounted, onUnmounted } from 'vue'
function useMouse() {
    const x = ref(0)
    const y = ref(0)
    const update = e= > {
      x.value = e.pageX
      y.value = e.pageY
    }
    onMounted((a)= > {
      window.addEventListener('mousemove', update)
    })
    onUnmounted((a)= > {
      window.removeEventListener('mousemove', update)
    })
    return { x, y }
  }
export default useMouse;
Copy the code

OnMounted, onUnmounted, update (useMouse), useMouse (useMouse), useMouse (useMouse) The service can then be used in any component without restriction.

Use the services provided by listenMouse in the component as follows:

<template>
    <p>Mouse Position:</p>
    <p>x:{{ x }},y:{{ y }}</p>
</template>
<script>
import useMouse from './listenMouse';
export default {
    setup (props) {
        let {x, y} = useMouse();
        return {
            x,
            y
        }
    }
}
</script>
Copy the code

Using the Composition API, you’ll find that the logic is easy to reuse, and the code is very clean, as shown below (just focus on the color block location) :

Here, the same color area represents the same function module, you can clearly see that the color blocks are orderly, a piece of code, reflecting the clean code, we need to modify which function, which code can be directly modified.

This is the Composition API, which we can use boldly when the logic between components needs to be reused and when the code within components needs to be stripped away.

How

With a look at the Composition API, you’ll notice one big change in code organization: the magic this in Vue2. X has been eliminated.

In Vue2. X, this is used extensively in our code. Props, data, and methods in components are bound to this context and accessed by this.

The Compositon API provides flexibility when it comes to extracting and reusing logic across components. A synthesized function depends only on its parameters and the globally introduced Vue APIs, not the magic of this context. We simply extract the part of the component that you want to reuse and export it as a function.

For example, listenmouse.js, exported separately from useMouse, can be used in other components.

However, every coin has two sides

disadvantages

Recently, I saw some people using the Composition API to practice the application, which is not very functional. After reading the Composition API, I think there will be a problem of “spaghetti code” in Vue3.0.

What is “spaghetti code”?

Noodle code: The control structure of the code is complex, confusing, illogical, and coupled, making it difficult to understand.

A visual example of noodle code:

This diagram is so confusing that it’s all mixed up like spaghetti, and it’s hard to figure out exactly how the call entrances and calls relate to the code.

Why worry about “noodle code”?

Options API and Composition API we have analyzed the differences between the Options API and Composition API.

Options API conventions:

  • We need to set the receive parameters in props
  • We need to set variables inside data
  • We need to set computing properties in computed
  • We need to set the listening properties in watch
  • We need to set event methods inside methods

You’ll notice that the Options APi dictates where we should do what, which in turn forces us to split code to some extent.

Now with the Composition API, this is no longer the convention, so the organization of code is very flexible, and our control code can be written inside the Setup.

If you are a beginner or a coder who doesn’t think seriously, the setup code will become more and more complex as the logic becomes more and more complex, and you will inevitably fall into the middle of “noodle code”.

Take, for example, the Composition API practice I reviewed above. It’s not a big application, but a setup method is 350 lines long…

How to get around it?

We have no this context and no enforced code separation of the Options API. The Composition API gives us more scope, so we need to be more careful about making appointments.

For complex logical code, we should pay more attention to the original intention of the Composition API, and do not be afraid to use the Composition API to separate the code and export it into various modules.

Here’s what we expect:

import useA from './a';
import useB from './b';
import useC from './c';

export default {
    setup (props) {
        let { a, methodsA } = useA();
        let { b, methodsB } = useA();
        let { c, methodsC } = useC();
        return {
            a,
            methodsA,
            b,
            methodsB,
            c,
            methodsC
        }
    }
}
Copy the code

Even as the setup content code gets bigger and bigger, it’s always going to be big, clean and uncluttered.

Setup is our code controller, so try not to write too much business logic code. Always adhering to the “controller to share the burden, to reduce the burden of setup” idea to code!

Of course, we also need to avoid the curse of falling into “chaotic code.” Also need to uphold: high cohesion, low coupling code policy.

Let’s wait for the official release of Vue3.0!

Welcome to pay attention to my wechat public number, do together reliable front end!