Directory:

  1. Review: Our current programming model.
  2. That is the result of hooks.
  3. Vue hooks, basic use of composition-API
  4. How do I understand composition-API using experience and experience?
  5. Programming paradigms: Object-oriented and functional programming.
  6. Finally, I heard some advice worth sharing from my predecessors.

1. Review: Our current programming model

First of all, there is a question. Isn’t our framework pretty good? Why study composition-API?

To answer this question, we need to look at our current programming model. What are the features of our current programming model? And what kind of problems will you encounter during development?

To answer this question, we need to go back to our current framework, to understand it, and let’s go back to where it started, when we were creating an application:

// main.js

// We instantiate a Vue class

new Vue({

  render: (h) = > h(App),

}).$mount('#app');
Copy the code

When we write a component

<template>

  <div></div>

</template>

<script>

// We return an object

export default {

  data(){},computed: {},methods: {}};</script>
Copy the code

We can see that our current programming mode is completely based on the idea of object-oriented development, according to the object-oriented programming characteristics, encapsulation, inheritance, polymorphism, in fact, this has met almost all the needs of our daily development. Object orientation is certainly comprehensive, but is there a downside to object orientation? Or is there a downside to object orientation in front-end development?

  1. Binding relationships are long, complex, and poorly readable
  2. thisThe direction of is easy to confusion, resulting in a large increase in the probability of error

That is the result of hooks

React released its first radical solution on February 4, 2019. Hooks were released in V16.8.0. As they had done in React, hooks changed front-end programming thinking once again. I won’t have to; Since the direction of this is not clear, we will eliminate this. When the head of this pointer falls to the ground, it also marks the death of object orientation in the front. Thus, the age of great Navigation officially arrives. After blowing up the front end development model, Vue finally released Vue 3.0 on September 18, 2000. The One-piece was finally available to the public! Vue delivered his answer to hooks, and composition-API was finally released. Vue 3 was renamed Vue – Core on February 7th of this year. Fruit power finally awakened!

3. Basic use of Composition-API

It should be noted that we did not use Vue3 in the project, but instead introduced @vue/ composition-API for composition-API development in the 2.x project for the following reasons:

  1. Although the compatibility of proxy has accounted for 93%, the other 2% of users still want to consider, after all, just come out

  1. The biggest reason is that the project is stable and refactoring is expensive, so it makes sense to use composition-API without major surgery.

Now I’m going to use it,

Basically, create a reactive variable
// composition-api

import {

  ref, reactive, defineComponent

} from '@vue/composition-api';

export default defineComponent({

  setup() {

    const num = ref(0)

    const people = reactive({

      name: "Bob".age: 18

    })

    / /!!!!!! Note: values created by ref must be accessed using.value

    console.log(num.value) / / 0

    console.log(people) // { name: "Bob",age: 18 }

    return {

      num,

      people

    }

  }

})
Copy the code
Add events to the DOM element
<template>

  <div @click="tapMe">BUTTON</div>

</template>

<script>

// composition-api

import {

  defineComponent

} from '@vue/composition-api';

export default defineComponent({

  setup() {

    const tapMe = () = > {

      console.log(111)}return {

      tapMe

    }

  }

})

</script>
Copy the code
And communication related props, computed, $emit…
// composition-api

import{defineComponent, ref, computed}from '@vue/composition-api';

export default defineComponent({

  props: {

    text: {

      type: String.default: The '-'}},setup(props, { emit }) {

    const { text } = props

    

    const money = ref(0)

    const moneyText = computed(() = > `${money.value}Yuan `)

    const send = () = > {

      emit('change', moneyText)

    }

    return {

      money,

      moneyText,

      send

    }

  }

})
Copy the code
Finally, get an instance of the root component
// composition-api

import {

  defineComponent

} from '@vue/composition-api';

export default defineComponent({

  setup(props, { root }) {

    const toPageIndex = () = > {

      root.$router.push({

        path: '/index'})}return {

      toPageIndex

    }

  }

})
Copy the code

I can tell from the length that it’s pretty easy to use, but here’s the thing: I don’t see any benefit in it. I don’t see any reduction in the amount of code. And all the code is crammed into the setup function. Are you sure the composition-API wasn’t created for KPIs? Don’t worry, let’s take a look.

4. My understanding of composition-API

  1. The amount of code is the same, but the logic is clearer and the readability is better

In fact, there is a very good explanation on the official website, the following is an edited version of our previous code:

Each color represents the relevant logic of each business logic, as you can see, the code is all mixed together, if the elder brother’s code is too large, write a thousand or two thousand lines of code, I believe that few people are willing to see such code.

You can see this by comparing the code. Let’s take a basic page as an example

Speaking in code, if we had written it this way before

export default {

  data() {

    return {

      banner: ' '.tab: {

        index: 0

      },

      list: []}},computed: {},methods: {

    clickBanner() {

      console.log('clickBanner')},setBanner(value) {

      this.banner = value

    },

    changeTab(value) {

      this.tab.index = value

    },

    setList(list) {

      this.list = list

    },

    clickItem(item) {

      console.log('clickItem', item)

    }

  },

};
Copy the code

But that’s what happens when we use composition-API

import {

  ref, reactive, defineComponent

} from '@vue/composition-api';

export default defineComponent({

  setup() {

    // Logic related to the banner

    const banner = ref(' ')

    const clickBanner = () {

      console.log('clickBanner')}const setBanner = (value) {

      banner.value = value

    }

    // Tab-related logic

    const tab = reactive({

      index: 0

    })

    const changeTab = (value) {

      tab.index = value

    }

    // List related logic

    const list = ref([])

    const setList = (list) = > {

      list.value = list

    },

    const clickItem => (item) {

      console.log('clickItem', item)

    }

    

    return {

      // Logic related to the banner

      banner,

      clickBanner,

      setBanner,

      // Tab-related logic

      tab,

      changeTab,

      // List related logic

      list,

      setList,

      clickItem,

    }

  }

})
Copy the code

The logic associated with each business code stands close together so that the code is clear and easy to read. Is that all it takes? Wouldn’t it be the same if we split the components a little bit more granular? We split banner, Tabs, List, and other components one by one to fine-grained components.

It is indeed possible to do this, and we did this in our previous business development, but then the product added requirements, for example:

My banner may be a round broadcast, may be a picture

I even have a different UI length for my List on each page, and even my items are different. There are also some other logic, such as the top 3 of the List need to be displayed separately

I also need a PC side of this page, the banner PC side with a different field

Since the PC mobile terminal is to be separated, it is necessary to realize the separation of UI and logic. In order to solve this problem, we proposed a solution of UI component and business component.

As shown in the figure above, the problem is solved, but we can see that the business granularity is becoming finer and higher, and the components are becoming more and more nested. It’s like we’re in infinite nesting mode. In the actual development found that this will bring one of the simplest problems, if you want to transform a page UI, you have to deal with all kinds of communication, components of various split, too complex, it is possible that you would rather CTRL + CV a set of code is not willing to dismantle the components, more willing to maintain PC, mobile terminal two sets of code.

Will composition-API solve the problem? I can tell you for sure, yes!

Let’s tweak the code a bit and customize the hooks

// hooks.js

import {

  ref, reactive

} from '@vue/composition-api';

// Logic related to the banner

export function useBanner () {

    const banner = ref(' ')

    const clickBanner = () {

      console.log('clickBanner')}const setBanner = (value) {

      banner.value = value

    }

    return {

      banner,

      clickBanner,

      setBanner,

    }

}

// Tab-related logic

export function useTab() {

    const tab = reactive({

      index: 0

    })

    const changeTab = (value) {

      tab.index = value

    }

    return {

      tab,

      changeTab

    }

}



// component.js 

import {

  defineComponent

} from '@vue/composition-api';

import { useBanner, useTab } from './hooks'



export default defineComponent({

  setup() {

    // Logic related to the banner

    const {

      banner,

      clickBanner,

      setBanner,

    } = useBanner()

    // Logic related to the banner

    const {

      tab,

      changeTab

    } = useTab()

    return {

      banner,

      clickBanner,

      setBanner,

      tab,

      changeTab,

      // List related logic

      // ...}}})Copy the code

This makes the UI completely separate from the components, and the code visible to the eye is clearer, and since it is function referenced, we can only import code that is relevant to my business, so the code is clear, and the CLI is much better at compressing the code when packaging tree-shaking because of the clarity of import and use.

5. Topic: Programming paradigms – Object-oriented and functional programming

We just saw a great separation of UI and logic with composition-API. But why didn’t our initial object orientation work? This brings us back to the programming paradigm

When we talk about object orientation, we always try to abstract out a class, and a class has two basic concepts, one is a property, the other is a method. After class instantiation, return one object we need, the object returned by instantiation will inherit all the attributes of the class, and the object binding method is to change the state of the object. In our framework, the state becomes data, and the method becomes methods. Methods are strongly related to data, and data is bound to our page UI, so that is why they cannot be separated.

Comaction-api is an outgrowth of functional programming, which is all about inputs and outputs. Functions are inherently isolated, and in the case of comaction-API, I must have a return value for you anyway, so the UI just tells it which return value it needs to bind to. Setup takes care of the mapping between the output and the page UI, which is why composition-API must be in Setup.

6. Advice worth sharing

  1. Pay attention to the body

No joke, many predecessors have occupational diseases, non-standard use of the keyboard led to the mouse hand, sedentary hemorrhoids, long-term bow at the desk cervical spondylosis… . Here is a reminder for you and yourself: exercise and drink water.

  1. Don’t have to be inferior to BAT

For example, we may think that our technology will never be as good as that of the bat developers. Here, we need some spiritual victory methods. We think that we are in fact the same as bat developers. They’re just a little bit more technical than we are. They might have used composition-API earlier and we would have learned it. They may use TS better, so I will learn it too; Maybe they are more solid at the bottom, so we can make it up, so that we can reach the corresponding level one day

The End

Encourage each other!