Environment set up

$ git pull https://github.com/vuejs/vue-next.git
$ cd vue-next && yarn
Copy the code

Once the download is complete, open the code and turn on sourceMap:

  • Tsconfig. json changes the sourceMap field to true: “sourceMap”: true

  • Rollup.config. js In rollup.config.js, manually type output.sourcemap = true

  • Generate the vUE global file: yarn dev

  • Create a demo directory in the root directory to store the sample code, and create an HTML file in the Demo directory to import the built Vue file

API use is very simple, below the content, see the example code can understand, so the following example will not do too much explanation.

reactive

Reactive: Creates reactive data objects

The setup function is a new entry function that is equivalent to beforeCreate and Created in vue2.x. It is executed after beforeCreate and before Created.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>reactive</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive } = Vue
    const App = {
        template: `
            <button @click='click'>reverse</button> 
            <div style="margin-top: 20px">{{ state.message }}</div>
        `,
        setup() {
            console.log('setup ');

            const state = reactive({
                message: 'Hello Vue3!! '
            })

            click = () => {
                state.message = state.message.split(' ').reverse().join(' ')}return {
                state,
                click
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

ref & isRef

Ref: creates a responsive data object isRef: checks whether the value is a reference to ref.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>ref & isRef</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, isRef } = Vue
    const App = {
        template: `
            <button @click='click'>count++</button> 
            <div style="margin-top: 20px">{{ count }}</div>
        `,
        setup() {
            const count = ref(0);
            console.log("Count. The value.", count.value)  // 0

            count.value++
            console.log("Count. The value.", count.value) // 1 // Check whether a value is a responsive type console.log('count is ref:', isRef(count))

            click = () => {
                count.value++;
                console.log(Value: "click count.", count.value) 
            }

            return {
                count,
                click,
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

Template Refs

When using the Composition API, the concepts of reactive and template references are unified.

To get a reference to an element or component instance in the template, we can declare ref and return it from setup() as usual.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>Template Refs</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, isRef, toRefs, onMounted, onBeforeUpdate } = Vue
    const App = {
        template: `
            <button @click='click'>count++</button> 
            <div ref="count" style="margin-top: 20px">{{ count }}</div>
        `,
        setup() { const count = ref(null); onMounted(() => { // the DOM element will be assigned to the ref after initial render console.log(count.value) // <div/>  }) click = () => { count.value++; console.log(Value: "click count.", count.value) 
            }

            return {
                count,
                click
            }
        }
    }
    
    createApp(App).mount('#app')
</script>
</html>Copy the code

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>Template Refs</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, isRef, toRefs, onMounted, onBeforeUpdate } = Vue
    const App = {
        template: `
            <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
                {{ item }}
            </div>
        `,
        setup() {
            const list = reactive([1, 2, 3])
            const divs = ref([])

            // make sure to reset the refs before each update
            onBeforeUpdate(() => {
                divs.value = []
            })

            onMounted(() => {
                // the DOM element will be assigned to the ref after initial render
                console.log(divs.value) // [<div/>]
            })

            return {
                list,
                divs
            }
        }
    }
    
    createApp(App).mount('#app')
</script>
</html>Copy the code

toRefs

ToRefs: Converts a reactive data object into a single reactive object

A Reactive proxy object is flattened and converted to a REF proxy object so that its properties can be used directly on the template.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>toRefs</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, isRef, toRefs } = Vue
    const App = {
        // template: `
        //     <button @click='click'>reverse</button> 
        //     <div style="margin-top: 20px">{{ state.message }}</div>
        // `,
        // setup() {
        //     const state = reactive({
        //         message: 'Hello Vue3.0!!!!! '
        //     })

        //     click = () => {
        //         state.message = state.message.split(' ').reverse().join(' ')
        //         console.log('state.message: ', state.message)
        //     }

        //     return {
        //         state,
        //         click
        //     }
        // }

        template: `
            <button @click='click'>count++</button> 
            <div style="margin-top: 20px">{{ message }}</div>
        `,
        setup() {
            const state = reactive({
                message: 'Hello Vue3.0!!!!! '
            })

            click = () => {
                state.message = state.message.split(' ').reverse().join(' ')
                console.log('state.message: ', state.message)
            }

            return{ click, ... toRefs(state) } } } createApp(App).mount('#app')
</script>
</html>Copy the code

computed

Computed: Create computed attributes

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>computed</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, computed } = Vue
    const App = {
        template: `
            <button @click='handleClick'>count++</button> 
            <div style="margin-top: 20px">{{ count }}</div>
        `,
        setup() {
            const refData = ref(0);

            const count = computed(()=>{
                returnrefData.value; }) const handleClick = () =>{refdata. value += 1 // To modify count dependency refData} console.log()"refData:" , refData)

            return {
                count,
                handleClick
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>computed</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, computed } = Vue
    const App = {
        template: `
            <button @click='handleClick'>count++</button> 
            <div style="margin-top: 20px">{{ count }}</div>
        `,
        setup() {
            const refData = ref(0);

            const count = computed({
                get() {return refData.value;
                },
                set(value){
                    console.log("value:", value) refData.value = value; }}) const handleClick = () =>{count.value += 1} console.log(refData)return {
                count, 
                handleClick
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

watch & watchEffect

Watch: Creates a Watch listener

WatchEffect: This function is triggered if the responsiveness property changes

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>watch && watchEffect</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, watch, watchEffect } = Vue
    const App = {
        template: `
            <div class="container">
                <button style="margin-left: 10px" @click="handleClick()"< p style= "max-width: 100%; clear: both"margin-left: 10px" @click="handleStop"< p style= "max-width: 100%; clear: both; min-height: 1em"margin-left: 10px" @click="handleStopWatchEffect"<div style= "color: RGB (51, 51, 51)"margin-top: 20px">{{ refData }}</div>
            </div>`
        ,
        setup() {
            let refData = ref(0);

            const handleClick = () =>{
                refData.value += 1
            }

            const stop = watch(refData, (val, oldVal) => {
                console.log('watch ', refData.value)
            })

            const stopWatchEffect = watchEffect(() => {
                console.log('watchEffect ', refData.value)
            })

            const handleStop = () =>{
                stop()
            }

            const handleStopWatchEffect = () =>{
                stopWatchEffect()
            }

            return {
                refData, 
                handleClick,
                handleStop,
                handleStopWatchEffect
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

v-model

V-model: bi-directional binding

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>v-model</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, watchEffect } = Vue
    const App = {
        template: `<button @click='click'>reverse</button> 
                    <div></div>
                    <input v-model="state.message" style="margin-top: 20px" />
                    <div style="margin-top: 20px">{{ state.message }}</div>`,
        setup() {
            const state = reactive({
                message:'Hello Vue 3!! '
            })

            watchEffect(() => {
                console.log('state change ', state.message)
            })

            click = () => {
                state.message = state.message.split(' ').reverse().join(' ')}return {
                state,
                click
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

readonly

Using the readonly function, you can return an object, a Reactive object, and a REF object as read-only objects.

Return a readonly object that will be warned on console if it changes.

The program will still run without error.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>readonly</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, readonly, watchEffect } = Vue
    const App = {
        template: `
            <button @click='click'>reverse</button> 
            <button @click='clickReadonly' style="margin-left: 20px">readonly++</button> 
            <div style="margin-top: 20px">{{ original.count }}</div>
        `,
        setup() {
            const original = reactive({ count: 0 })

            const copy = readonly(original)

            watchEffect(() => {
                // works forreactivity tracking console.log(copy.count) }) click = () => { // mutating original will trigger watchers relying on the  copy original.count++ } clickReadonly = () => { // mutating the copy will fail and resultin a warning
                copy.count++ // warning!
            }

            return {
                original,
                click,
                clickReadonly
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

provide & inject

Enable dependency injection similar to the 2.x provide/inject option.

Both can only be called during setup(), the current active instance.

import { provide, inject } from 'vue'

const ThemeSymbol = Symbol()

const Ancestor = {
  setup() {
    provide(ThemeSymbol, 'dark')
  }
}

const Descendent = {
  setup() {
    const theme = inject(ThemeSymbol, 'light' /* optional default value */)
    return {
      theme
    }
  }
}Copy the code

Inject accepts an optional default value as the second parameter.

Inject returns undefined if a default value is not provided and the attribute is not found in the Provide context.

Lifecycle Hooks

Comparison of Vue2 and Vue3 life cycle hooks:

Vue2 Vue3
beforeCreate The setup (alternative)
created The setup (alternative)
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured
empty onRenderTracked
empty onRenderTriggered

In addition to the 2.x lifecycle equivalents, the Composition API provides the following debug hooks:

  • onRenderTracked
  • onRenderTriggered

Both hooks receive a DebuggerEvent, similar to the onTrack and onTrigger options for observers:

export default {
  onRenderTriggered(e) {
    debugger
    // inspect which dependency is causing the component to re-render
  }
}Copy the code

Example:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello Vue3.0</title> <style>#app {
            text-align: center;
            padding: 30px;
        }
    </style>
    <script src=".. /.. /packages/vue/dist/vue.global.js"></script>
</head>
<body>
    <h3>Lifecycle Hooks</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, onMounted, onUpdated, onUnmounted } = Vue
    const App = {
        template: `
            <div class="container">
                <button @click='click'>reverse</button>
                <div style="margin-top: 20px">{{ state.message }}</div>
            </div>`
        ,
        setup() {
            console.log('setup! ')

            const state = reactive({
                message: 'Hello Vue3!! '
            })

            click = () => {
                state.message = state.message.split(' ').reverse().join(' ')
            }

            onMounted(() => {
                console.log('mounted! ')
            })
            onUpdated(() => {
                console.log('updated! ')
            })
            onUnmounted(() => {
                console.log('unmounted! ')})return {
                state,
                click
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>Copy the code

The last

This article only lists the apis that I think will be used a lot. There are many new features in Vue3.0, such as customRef and markRaw, and you can see the Vue Composition API documentation if you are interested.

  • Vue Composition API: composition-api.vuejs.org/api.html#se…

  • Vue-next address: github.com/vuejs/vue-n…

Reference article:

  • Vue3 early adopters

Recommended reading:

1. Blockbuster: GitHub 100K+ Star front-end interview open source project summary (necessary for entering big factories)

  1. Highly recommended: GitHub 170K+ Star front-end learning data Structures and algorithms project

  2. A diagram to clarify the Vue 3.0 responsive system, to achieve a streamlined version of the responsive system

  3. Dark Learning: GitHub mining Magic Tips – How to find great open Source projects