Vue3 the favorite --Composition API reading for you

Author: Filip Rakowski

Translation: Kai Road School


We already know that in the preparation of the new version of Vue application will behave very well, but the performance is not the most important part. For us developers, the most important thing is how the new version will affect the way we write the code.

As you might expect, Vue3 brought many new exciting features. Fortunately, Vue team principal for the current Composition API has been added and improvements rather than a major change, so people should already know Vue2 quickly satisfied with the new syntax.

Let the majority of people may have heard of Composition API start!

Composition API

The most common is the characteristic syntax Composition AP of the next major version of Vue discussed. This is a new logic and code reuse organizational methods.

Currently, we are using the "options" API to build components. To add to the logic assembly Vue, we filled (options) attributes, such as data, methods, computed like. The biggest drawback of this approach is, JavaScript code is itself not a job. You need to know exactly what the template attributes and behavior of this key can access. At the bottom, Vue compiler needs to convert this property into working code. Because of this, we can not recommend or benefit from automatic type checking.

Composition API hope to mechanisms available for the public JavaScript function to solve this problem with the current component properties. Vue assembly Composition API core team will be described as "an additional set of basis functions api, logic allows flexible combination of components." Use Composition API to write code more readable, and the scene is not complicated, which makes it easier to read and learn.

Let's see an example of a very simple component, which uses new components Composition API to understand how it works.

<template>
  <button @click="increment">
    Count is: {{ count }}, double is {{ double }}, click to increment.
  </button>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const double = computed(() => count.value * 2)

    function increment() {
      count.value++
    }

    onMounted(() => console.log('component mounted!'))

    return {
      count,
      double,
      increment
    }
  }
}
</script>

Now let's put this code into several sections to understand what is happening.

import { ref, computed, onMounted } from 'vue'

As I mentioned earlier, Composition API will open as a function of component properties, so the first step is to import the function we need. In the case, we need to create a responsive reference with the ref, calculate properties using computed, with the life cycle of onMounted access hook after loading.

Now you may be wondering what this mysterious setup method?

export default {
  setup() {}
    }
    ```
简而言之,它只是一个函数,它将属性和函数返回到模板。  我们在这里声明所有的响应式属性、计算属性、观察者和生命周期钩子,然后返回它们,以便它们可以在模板中使用。 我们没有在setup函数返回的内容将在模板中不可用。 

```js
const count = ref(0)

According to the above, we call the count of responsive property with ref function declaration. It may be packaged in any primitive or object type, and returns its reference responsive. The value of the transfer elements will remain in creating a reference value of the property. For example, if you want to access the value of the reference count, we need to extend the request count.value.

const double = computed(() => count.value * 2)

function increment() {
  count.value++
}

This is what we did in the calculation of property declaration and double increment function

onMounted(() => console.log('component mounted!'))

Mounted within the hook, when the assembly is loaded, you can record some information

return {
  count,
  double,
  increment
}

In the end, we return and double count increment properties and methods so that they can be used in the template.

<template>
  <button @click="increment">
    Count is: {{ count }}, double is {{ double }}. Click to increment.
  </button>
</template>

We can now access the properties and functions of the template setup return, just as they are by the old options API declarations of the same.

This is a simple example, use Options API also very easy to achieve this. The real benefit of the new Composition API is not only to write code in different ways, but also in the reuse our code / logic, these benefits will emerge.

Composition API code reuse

New Composition API has more advantages. Think of code reuse, at present, if we want to share some code between other components, there are two options available - mix and range of slots. Both have their drawbacks.

Suppose we want to extract count function and reuse it in other components, below you can see how to use it with the available API and Composition API.

We start from mixing ......

import CounterMixin from './mixins/counter'

export default {
  mixins: [CounterMixin]
}

The biggest shortcoming is mixed: we do not know it gives us what components increased. It is not only difficult to explain, but also may lead to name conflicts with existing properties and functions.

Take a look at the range of slots

<template>
  <Counter v-slot="{ count, increment }">
     {{ count }}
    <button @click="increment">Increment</button> 
  </Counter> 
</template>

Use of slots, we know exactly which properties we can access the property by v-slot, making it easier to understand the code. The disadvantage of this method is that we can only access it in the template, it can only be used within the Counter component range.

It's time to use the Composition API

function useCounter() {
  const count = ref(0)
  function increment () { count.value++ }

  return {
    count,
    incrememt
  }
}

export default {
  setup () {
    const { count, increment } = useCounter()
    return {
      count,
      increment
    }
  }
}

More elegant, is not it? We unrestricted range of templates and components, and we know exactly which properties can be accessed from the counter. In addition, we can benefit from the code compiled, since useCounter just a function of the return of certain property. So Editor can help us type checking and advice.

It also uses a third-party library of more elegant way. For example, if we want to use vuex, we can extend useStore function rather than pollution Vue prototype (this. $ Store).

const { commit, dispatch } = useStore()

image

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/105029324