The late VUE3 article actually covered VUE3 back in March this year.

relearned TypeScript at the end of last year in order to get into Vue3 cars and drive them better.

After two weeks of development, I finally went online. During this period, I also encountered many small pits, many of which were nowhere to be found. After slowly thinking, I finally overcame them.

Vue3 + TypeScript Study

First, environment configuration

1.1 Install the latest VUE scaffolding

npm install -g @vue/cli

yarn global add @vue/cli

1.2 Create a Vue3 project

vue create projectName

1.3 Upgrade existing VUE 2 projects to VUE3

vue add typescript

Two, attack VUE3

2. 1 VUE 2 limitations

  1. Components are difficult to read and maintain as they grow in size with their dependencies
  2. There is no perfect solution to cross-component code reuse

2.2 How does Vue 3 solve Vue 2 limitations

  1. Components are difficult to maintain and manage

Write compositing functions in VUE3, using the Compositon API Setup.

  1. There is no perfect solution to cross-component code reuse

Vue3 Composition AP I

3.1 About Composition API

In VUE3, it is also possible to write components without the Composition API, which is just another way of writing components in VUE3, and internally simplifies a lot of things.

So you can continue to write components the way Vue2 does.

3.2 When to use Composition API

  1. TypeScript ` support
  2. Can be used when writing large components Composition ApiComposed functions are good for managing state
  3. When code is reused across components

Four,Composition API prerequisite

4.1 what issetup

SetUp is another implementation for configuring component state.

In order for a method to be used in a template, it must return the state defined in SetUp


  • setupMethod is in components , props data Methods Computed Lifecycle methodsBefore performing
  • At the same time setupIs not accessible in this

4.2 refCreate responsive variables

In VUE2, we defined a reactive variable that we could define directly in data and use in the template. If we use the composition API, we need to create a response variable using Ref in setup and return it for use in the page.


    1. The introduction of ref import { ref } from 'vue'
    1. The initial variableConst name = ref(' ref('))
    1. Returns the variable return { name } You can also return methods in a return
    1. in setupCan not be obtained directly from the variable name,The object and value must be obtained by the variable name. Value

Such benefits

  • The states are easy to manage and can be divided into several setupState management, finally import all in a file, and use.
<template> <div> <h1>{{title}}</h1> </div> </template> <script> import {ref,defineComponent} from 'vue' export default DefineComponent ({setup () {// Define the responsive variable const title = ref(' front-end self-study community ') // Access the variable console.log(tit.value) // Return the variable {title} } }) </script>

4.3 The life cycle

Composition API life cycle hooks have the same name as the Vue 2 option life cycle hooks, except that they are prefixed on, onMounted ‘when using Composition APIs


There are two mounted life hooks in the following code. Which one do you think will be executed first?

setupWill be performed

SetUp (){// SetUp (const title = ref(' front-end self-study community ') console.log(title) // SetUp (){ Console. log(title.value)} // OnMounted (getTitle) return {title}}, Mounted() {console.log(' Test Mounted Execution Sequence ')},

4.4 watch

Use watch responsive changes in setup

  • Introducing the watch, import { watch } from 'vue'
  • Use watch directly. Watch accepts three parameters

    1. The reactive reference or getter function to listen for updates
    2. A callback to do the updated operation
    3. Optional configuration
Import {wathc} from 'vue' const num = ref(0) // function changeNum(){num.value++} // wathc listens for var (const num = ref(0)) Watch (num,(newValue, oldValue) = bb0 {console.log(' newValue is: ${newValue},--------oldValue is: ${oldValue} ')})

4.5 computed

It is also a read-only reactive reference imported from VUE, and a computed function returns the output of a getter class callback passed as the first argument to computed. To access the value of the newly created computed variable, we need to use the.value property as if we were using ref.

When num changes, the value of nums is *3

import {ref,computed} from 'vue'; Const num = ref(0) // const num function changeNum(){num.value++} // const nums = computed(() =>{return num 3})


5.1 Accept two parameters

Props: A property passed by the parent component. Setup functions props are responsive and will be updated as the data is updated and cannot be destructed using ES6 because it will not make props responsive.

Context: This is a normal object that exposes the · properties of three components

  1. Attribute
  2. slot
  3. Triggering event

contextIt is not reactive, so you can use ES6 deconstruction to simplify the notation.

     setup (props,{attrs,slots,emit}) {

5.2 Component loading setupPay attention to when

When the component executes Setup, the component instance is not created, so the following properties cannot be accessed

  • data
  • computed
  • methods

Six,The life cycle

When using the lifecycle in Setup, the prefix must be on.

Option type API Hook inside setup
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

Passing values across components

In Vue 2, we can use Provide/Inject to pass values across components, as well as in Vue 3.

Used in Setup, must be imported from Vue.

When using Provide, it is typically set to update in a responsive manner, so that the parent component changes, the child component, and the descendant component also update.

How do I set it to update responsively?

  1. use ref / reactiveCreate responsive variables
  2. useProvide ('name', 'reactive variable to pass ')
  3. Finally, add an event that updates the reactive variable so that the reactive variable updates, provideVariables in the.

The parent component

Parent import {provide, defineComponent, ref, reactive} from "vue"; <template> <Son/> </template> <script> import { provide, defineComponent, ref, reactive } from "vue"; Export default defineComponent({setup() {const father = ref(" my parent ")); Const info = reactive({id: 23, message: "front-end self-study community ",}); Function changeProvide(){info.message = 'test'} provide('father',father) provide('info',info) return {changeProvide}; } }) </script>

Child components


import {provide, defineComponent,ref,reactive, inject} from 'vue'
export default defineComponent({
    setup () {
        const fatherData = inject('father')
        const info = inject('info')
        return {fatherData,info}

Use typesCirpt techniques in Vue

8.1 Interface Constraint Constraint Properties

TypeScirptType assertion + interface perfectly constrains properties

Export default interface queryType{page: Number, size: Number, name: String, age: Number}
Used in the component
import queryType from '.. /interface/Home' data() {return {query:{page:0, size:10, name:' test ', age: 2} as queryType}},

The 8.2 component is used defineComponentdefine

TypeScriptCorrect inferences
VueType in the component options

import { defineComponent } from 'vue'

export default defineComponent({
        return{ }

8.3 Type declarationreactive

export default interface Product { name:String, price:Number, address:String } import Product from '@/interface/Product' import {reactive} from 'vue' const product = Reactive ({name:' Xiaomi 11',price:5999,address:' Beijing '}) as Product return {fatherData,info, Product}

The last

If there are any errors in this article, please feel free to correct them in the comments section. If you can help, please feel free to follow