It’s been a while since the beta version of Vue3.0 was released, and the official version is not far off, so it’s time to really learn the syntax of Vue3.0.

GitHub blog: github.com/biaochenxuy…

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>
        body.#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: `  
       
{{ state.message }}
`
, setup() { console.log('setup '); const state = reactive({ message: 'Hello Vue3!! ' }) click = (a)= > { 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>
        body.#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: `  
       
{{ count }}
`
, setup() { const count = ref(0); console.log("Count. The value.", count.value) / / 0 count.value++ console.log("Count. The value.", count.value) / / 1 // Determine if a value is of a reactive type console.log('count is ref:', isRef(count)) click = (a)= > { 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>
        body.#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: `  
       
{{ count }}
`
, setup() { const count = ref(null); onMounted((a)= > { // the DOM element will be assigned to the ref after initial render console.log(count.value) // <div/> }) click = (a)= > { 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>
        body.#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: ` 
       
{{ item }}
`
, setup() { const list = reactive([1.2.3]) const divs = ref([]) // make sure to reset the refs before each update onBeforeUpdate((a)= > { divs.value = [] }) onMounted((a)= > { // 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>
        body.#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: `
        // 
        // 
       
{{ state.message }}
/ / `, // setup() { // const state = reactive({ / / the message: 'Hello Vue3.0!!!!! ' / /}) // click = () => { // state.message = state.message.split('').reverse().join('') // console.log('state.message: ', state.message) / /} // return { // state, // click / /} // } template: `
{{ message }}
`
, setup() { const state = reactive({ message: 'Hello Vue3.0!!!!! ' }) click = (a)= > { 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>
        body.#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: `  
       
{{ count }}
`
, setup() { const refData = ref(0); const count = computed((a)= >{ return refData.value; }) const handleClick = (a)= >{ refData.value += 1 // Modify the 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>
        body.#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: `  
       
{{ count }}
`
, setup() { const refData = ref(0); const count = computed({ get(){ return refData.value; }, set(value){ console.log("value:", value) refData.value = value; }})const handleClick = (a)= >{ count.value += 1 // Change count directly } 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>
        body.#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: ` 
       
'
, setup() { let refData = ref(0); const handleClick = (a)= >{ refData.value += 1 } const stop = watch(refData, (val, oldVal) => { console.log('watch ', refData.value) }) const stopWatchEffect = watchEffect((a)= > { console.log('watchEffect ', refData.value) }) const handleStop = (a)= >{ stop() } const handleStopWatchEffect = (a)= >{ 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>
        body.#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: ` 
       
{{ state.message }}
`
, setup() { const state = reactive({ message:'Hello Vue 3!! ' }) watchEffect((a)= > { console.log('state change ', state.message) }) click = (a)= > { 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>
        body.#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: `   
       
{{ original.count }}
`
, setup() { const original = reactive({ count: 0 }) const copy = readonly(original) watchEffect((a)= > { // works for reactivity tracking console.log(copy.count) }) click = (a)= > { // mutating original will trigger watchers relying on the copy original.count++ } clickReadonly = (a)= > { // mutating the copy will fail and result in 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(a)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>
        body.#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: ` 
       
{{ state.message }}
`
, setup() { console.log('setup! ') const state = reactive({ message: 'Hello Vue3!! ' }) click = (a)= > { state.message = state.message.split(' ').reverse().join(' ') } onMounted((a)= > { console.log('mounted! ') }) onUpdated((a)= > { console.log('updated! ') }) onUnmounted((a)= > { console.log('unmounted! ')})return { state, click } } } createApp(App).mount('#app')
</script> </html> Copy the code

The last

GitHub blog: github.com/biaochenxuy… .

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