directory

  • How to debug Vue3 source code breakpoint in browser
  • Try Vue3 part two: The most important changes to the CompositionApi
  • Try Vue3 3: CompositionAPI summary and wrapping objects
  • How do I run Jest unit Tests
  • Try Vue3 five: source code structure
  • Try Vue3 six: innovation of responsive principle – Vue2, Vue3 implementation comparison

In the last article, we explained how to download and run the Vue3 Alpha source code. In this article we take a look at one of the most important RFC compositionapis in 3.0.

concept

The CompositionAPI can be translated as a composite API if only literally. It used to be called Vue Function-based API, but I think it’s more descriptive now. Essentially, the Position API was created to make it easier to implement combinations of logic.

Review of history

Vue2 to achieve logical compliance in components, for example, all button components should be shaken proof, the options are as follows:

  • Mixins
  • Higher-order Components (aka HOCs)
  • Renderless Components (based on Scoped slots/scope slots) encapsulate logical Components but all three are not very ideal, there are major problems
  • The source of template data is not clear, such as mixin just looking at the template it is difficult to tell where an attribute comes from.
  • Namespace conflict
  • Performance issues. HOC, for example, requires additional nesting of component logic, resulting in unnecessary performance overhead.

But I was more concerned with the primitive programming behavior of composing logic that I had to introduce other concepts to deal with. This, of course, is why many Java architects prefer React. Vue is the language of laughing in and crying out. Getting started might seem easy enough to just look at HelloWorld and work, but as soon as you run into problems you need to introduce a new concept. It’s not as clean and natural as the React function as a component.

motivation

So let’s take a look first

const App = {
            template: `  `,
            data() {
                return {
                    message: 'Hello Vue 3!! '}},methods: {
                click() {
                    console.log('click .... '.this.message)
                    this.message = this.message.split(' ').reverse().join(' ')}}}let vm = Vue.createApp().mount(App, '#app')
Copy the code

Options API source code location

The classic Vue API can be summarized as the Options API, which can be understood as the API for declaring logic in a configuration-based manner. What I mean is basically defined based. Think about vue2’s HelloWorld as if it had just completed a few simple definitions. I think this is why VUE is so popular and it’s really easy to describe the logic in general. Of course, it also has a lot to do with the fact that He is a designer. Don’t let CSS and HTML be completely defined code.

But this expression can be problematic once the business logic is complex. Because once the logic is complicated you can’t write it as a lump, you have to think about how to organize it, you have to think about extracting common parts of the logic and thinking about reuse, otherwise the program becomes very difficult to maintain. Which three reuse methods have been mentioned above on the one hand because of the new concept on the other hand because of the poor programming experience and performance issues.

The CompositionAPI was inspired by React Hooks (which I mostly admit). Good things need to be borrowed from this and you shouldn’t despise the chain. Using the function composition API, you can extract the association API into a composition function that encapsulates the associated logic and returns the state that needs to be exposed to the component as a reactive data source.

In actual combat

Okay, so the first piece of logic is the larger mouse position listening logic

    // Mouse position listening logic
    function useMouse() {
            const state = reactive({
                x: 0.y: 0
            })
            const update = e= > {
                state.x = e.pageX
                state.y = e.pageY
            }
            onMounted((a)= > {
                window.addEventListener('mousemove', update)
            })
            onUnmounted((a)= > {
                window.removeEventListener('mousemove', update)
            })
            return toRefs(state)
        }

Copy the code

There’s another piece of logic that we want to combine like a time logic that refreshes at any time

function useOtherLogic() {
            const state = reactive({
                time: ' '
            })
            onMounted((a)= > {
                setInterval((a)= > {
                    state.time = new Date()},1000)})return toRefs(state)
        }
Copy the code

In the real world we can assume that these two logics could be reused by many components, and think of how helpless you would be with mixin and hoc. But with the Position API, we just need to combine it and expose like this

       const MyComponent = {
            template: `<div>x:{{ x }} y:{{ y }} z:{{ time }} </div>`,

            setup() {
                const {
                    x,
                    y
                } = useMouse()
                // Use with other functions
                const {
                    time
                } = useOtherLogic()

                return {
                    x,
                    y,
                    time
                }
            }
        }
        createApp().mount(MyComponent, '#app')
Copy the code

React hooks… Full examples welcome star

Quick update at…..

directory

  • How to debug Vue3 source code breakpoint in browser
  • Try Vue3 part two: The most important changes to the CompositionApi
  • Try Vue3 3: CompositionAPI summary and wrapping objects
  • How do I run Jest unit Tests
  • Try Vue3 five: source code structure
  • Try Vue3 six: innovation of responsive principle – Vue2, Vue3 implementation comparison