preface

The late Vue3 article, in fact, as early as in March this year, Vue3 had been over. I relearned TypeScript at the end of last year in order to drive Vue3 cars better. In April of my last company, the superior assigned me to develop an internal Party affairs system. The front end of this system was developed by me alone, a B-end system with less complicated functions and requirements, which was directly developed by Vue3 + TypeScript + Element Plus. During two weeks of development, I encountered a lot of small holes, many of which had nowhere to look up. I gradually ponded over it and finally overcame it.

Vue3 + TypeScript Study

First, environment configuration

1.1 Install the latest Vue scaffolding

npm install -g @vue/cli

yarn global add @vue/cli
Copy the code

1.2 Creating a Vue3 Project

vue create projectName
Copy the code

1.3 Upgrade the existing Vue 2 project to Vue3

vue add typescript
Copy the code

Two, attack Vue3

2. Limitations of Vue 2

  1. Components are difficult to read and maintain as they grow from one component to another

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

2.2 How can Vue 3 overcome limitations of Vue 2

  1. Components are difficult to maintain and manage

Composing functions in Vue3 using 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 using the Composition Api, which is just another way to write components in Vue3, internally simplifying a lot.

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

3.2 When to use Composition Api

  1. TypeScript ` support

  2. When writing large components, you can use Composition Api Composition functions to manage state well

  3. When you reuse code across components

Four,Essential fundamentals of Composition Api

4.1 what issetup

Setup is another implementation for configuring component state.

A state defined in Setup that a method must return to be used in a template

Note:

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

4.2 refCreate reactive variables

In Vue2, we define a reactive variable that can be defined directly in data and used in the template. To use the Composition API, we would have to use ref in setup to create the reactive variable and return it to use in the page.

use

    1. The introduction ofref import { ref } from 'vue'
    1. The initial variableConst name = ref(' specify default ')
    1. Returns the variablereturn { name }You can also return a method in 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

  • States are easy to manage and can be divided into several setupState management, finally import all in one file, and use.
<template>
    <div>
        <h1>{{title}}</h1>
    </div>
</template>

<script>
import {ref,defineComponent} from 'vue'
export default defineComponent({
    setup () {
        // Define reactive variables
        const title = ref('Front-end Self-learning Community')
        
      	// Access this variable
        console.log(title.value)
        // Return variable
        return {title}
    }
})
</script>

Copy the code

4.3 The life cycle

The Composition Api lifecycle hook has the same name as the Vue 2 optional lifecycle hook, but is prefixed with ON, onMounted when using the composite Api

sd

Mounted health hooks (mounted health hooks)

Setup is executed first

    setup () {
        // Define reactive variables
        const title = ref('Front-end Self-learning Community')
        console.log(title)
        // Return variable
        function getTitle(){
            console.log(title.value)
        }
        // The page is loading
        onMounted(getTitle)
        return {title}
    },
    mounted() {
        console.log('Test Mounted execution order')},Copy the code

4.4 watch

Use watch reactive changes in Setup

  • Import {watch} from ‘vue’

  • Use watch directly. Watch accepts three parameters

    1. A reactive reference or getter to listen for updates
    2. A callback to do the updated operation
    3. This parameter is optional
import {wathc} from 'vue'

// Define reactive variables
const num = ref(0)
// Update the reactive variable
function  changeNum(){
            num.value++
}

// wathc listens for responsive variables
watch(
 num,(newValue, oldValue) = > {
 console.log(` newValue is:${newValue}, -- -- -- -- -- -- -- -- oldValue as follows:${oldValue}`)})Copy the code

4.5 computed

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

** When num is changed, nums is *3 **

import {ref,computed} from 'vue';

const num = ref(0)

/ / update the num
function  changeNum(){
   num.value++
 }
// Listen for num changes
 const nums = computed(() = >{
  return num.value * 3
 })
Copy the code

Five,setup

5.1 Accept two parameters

Props: property passed by the parent component. In the setup function, props is responsive, which is updated as data is updated and cannot be deconstructed using ES6 because it does 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 it can be easily written using ES6 deconstruction.

   props:{
        obj: {type:Object
        }
    },
     setup (props,{attrs,slots,emit}) {
            console.log(attrs)
            console.log(slots)
            console.log(emit)
         	console.log(props.obj)
     }
Copy the code

5.2 Component Loading setupPay attention to when

When the component executes setup, the component instance is not created, so the following properties are not accessible

  • data
  • computed
  • methods

Six,The life cycle

When using life cycles in setup, the prefix must be added on.

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

7. Pass values across components

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

Used in Setup and must be imported from VUE for use.

When using Provide, it is typically set to update in response, so that the parent component changes and the children and descendants update with it.

How do YOU set it up for reactive updates?

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

The parent component

The parent componentimport { 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 component);
    const info = reactive({
      id: 23.message: Front-end Self-learning Community});function changeProvide(){
      info.message = 'test'
    }
    provide('father',father)
    provide('info',info)
    return{changeProvide}; }})</script>
Copy the code

Child components

<template>
    <div>
        <h1>{{info.message}}</h1>
        <h1>{{fatherData}}</h1>
    </div>
</template>

<script>
import {provide, defineComponent,ref,reactive, inject} from 'vue'
export default defineComponent({
    setup () {
        const fatherData = inject('father')
        const info = inject('info')
        
        return {fatherData,info}
    }
})
</script>
Copy the code

Use TypeScirpt techniques in Vue

8.1 Interface Constraints Constraint attributes

Using TypeScirpt’s features, the type assertion + interface perfectly constrains properties

interface
Paged query field property type validationexport default  interface queryType{
    page: Number.size: Number.name: String.age:  Number
}
Copy the code
Use in components
import queryType from '.. /interface/Home'


    data() {
        return {
            query: {page:0.size:10.name:'test'.age: 2
            } as queryType
        }
    },
Copy the code

8.2 Components used to defineComponentdefine

This way TypeScript correctly inferences types in Vue component options

import { defineComponent } from 'vue'

export default defineComponent({
    setup(){
        return{}}})Copy the code

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}
Copy the code

Selected articles

1. Vue routing menu access/button access control permissions 2. Vue | routing guard interview, often 3. Vue components communication way of 8 kinds of 4. Vue Axios encapsulated in management 5. 15 high-frequency check 20 】 【 WeChat applet interview questions

More exciting articles on the home page

The last

If there is any error in this article, welcome code friends in the comment area, if you help, welcome to like and attention ~~~