Vue3 + TypeScript Development Summary

Vue3 + TypeScript Development Summary

Vue3 + TypeScript Learning

1. 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 Upgrading existing Vue 2 projects to Vue 3

vue add typescript

2. Attack on Vue3

2.1 Vue 2 Limitations

  1. As components and their dependencies grow larger, components become difficult to read and maintain.
  2. There is no perfect solution for cross-component code reuse

2.2 How Vue 3 solves the limitations of Vue 2

  1. Components are difficult to maintain and manage

[Write a composite function in Vue3 and use Compositon Api setUp to solve it]

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

3. Vue3 Composition API

3.1 About Composition API

In Vue3, you can also write components without using Composition Api . It is just another way to write components in Vue3, which simplifies many operations internally.

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

3.2 When to use the Composition API

TypeScript` supports writing large components, you can use Composition Api API to manage state and reuse code across components

4. Essential foundation of Composition API

4.1 What is setup

setup is another implementation used to configure component state.

The state defined in setup, the method must return if it is to be used in the template

Notice:

  • The setup method is executed before components, props, data methods, and computed lifecycle methods.
  • At the same time, this cannot be accessed in setup

4.2 ref Create responsive variables

In Vue2, we define a responsive variable directly in data and use the variable in the template. If we use the composition api, we have to use ref in setup to create a responsive variable and return it before we can use it on the page.

use:

  • Import ref import { ref } from 'vue'
  • Initial variable const name = ref('specify default value')
  • Return variable return { name } You can also return methods in return
  • To access the value of a variable defined in setup, you cannot directly obtain it through the variable name. You must use variable name.value to obtain the object and value.

The benefits of this:

  • The status is easy to manage. You can divide it into several setup status management, and finally import all in one file and use it.
<template>
    <div>
        <h1>{{title}}</h1>
    </div>
</template>

<script>
import {ref,defineComponent} from 'vue'
export default defineComponent({
    setup () {
        // Define responsive variables const title = ref('Front-end self-study community')
        
          // Access the variable console.log(title.value)
        // Return variable return {title}
    }
})
</script>

4.3 Lifecycle

The Composition API lifecycle hooks have the same name as the Vue 2 optional lifecycle hooks, except that when using the Composition API, they are prefixed with on, onMounted.

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

setup will execute first

setup () {
        // Define responsive variables const title = ref('Front-end self-study 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')
    },

4.4 watch

Use watch to react to changes in setup

1. Import watch, import { watch } from 'vue'

2. Use watch directly. Watch accepts 3 parameters

  1. A reactive reference or getter function to listen for updates
  2. A callback to perform the update operation
  3. Optional Configuration Items
import {wathc} from 'vue'

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

// wathc monitors the responsive variable watch(
 num,(newValue, oldValue) => {
 console.log(`newValue is: ${newValue},--------oldValue is: ${oldValue}`)
   }
 )

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-like 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 just like we did with a ref.

When the value of num changes, the value of nums will be *3

import {ref,computed} from 'vue';

const num = ref(0)

// Update num
function changeNum(){
   num.value++
 }
//Monitor num changes const nums = computed(() =>{
  return num.value * 3
 })

5. Setup

5.1 Accepting two parameters

props: The properties passed by the parent component. The props in the setup` function are responsive. They will be updated as the data is updated, and ES6 destructuring cannot be used because it will not make props responsive.

context: It is a normal object that exposes 3 components · property

  1. Attribute
  2. Slots
  3. Triggering Events

context is not responsive, so you can use ES6 destructuring to simplify the writing.

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

5.2 Note when loading component setup

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

  • data
  • computed
  • methods

6. Life Cycle

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

7. Transferring values ​​across components

In Vue 2 , we can use Provide/Inject to pass values ​​across components, and this is also possible in Vue 3.

Used in setup , must be imported from vue .

When using Provide , it is generally set to responsive update, so that when the parent component changes, the child components and descendant components are also updated.

How to set it up for responsive updates?

  1. Use ref / reactive to create responsive variables
  2. Use provide('name', 'responsive variable to be passed')
  3. Finally, add an event to update the responsive variables, so that when the responsive variables are updated, the variables in the provide are also updated.

Parent component:

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 component");
    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>

Subcomponents:

<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>

8. Tips on using TypeScript in Vue

8.1 Interface Constraints Constraint Attributes

Using the characteristics of TypeScirpt , type assertion + interface perfectly constrains the properties

interface

Paging query field attribute type verification:

export default interface queryType{
    page: Number,
    size: Number,
    name: String,
    age: Number
}

Used in components:

import queryType from '../interface/Home'


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

8.2 Components are defined using defineComponent

This way TypeScript correctly infers the types in the Vue component options

import { defineComponent } from 'vue'

export default defineComponent({
    setup(){
        return{ }
    }
})

8.3 Reactive Type Declarations

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:'北京'}) as Product
       
return {fatherData,info,product}

The above is the detailed content of the Vue3 + TypeScript development summary. For more information about Vue3 + TypeScript, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Practical record of Vue3 combined with TypeScript project development
  • Detailed example of using typescript to encapsulate axios in Vue3
  • How to use vue3+TypeScript+vue-router
  • Vue3 TypeScript implements useRequest details

<<:  Simple setup of VMware ESXi6.7 (with pictures and text)

>>:  Analysis of MySQL latency issues and data flushing strategy process

Recommend

Linux kernel device driver advanced character device driver notes

/****************** * Advanced character device d...

How to add Nginx proxy configuration to allow only internal IP access

location / { index index.jsp; proxy_next_upstream...

Why MySQL can ignore time zone issues when using timestamp?

I have always wondered why the MySQL database tim...

MySQL database migration quickly exports and imports large amounts of data

Database migration is a problem we often encounte...

How to upload and download files between Linux server and Windows system

Background: Linux server file upload and download...

A brief discussion on the efficiency of MySQL subquery union and in

Recent product testing found a problem that when ...

Chinese website user experience rankings

<br />User experience is increasingly valued...

Specific use of the wx.getUserProfile interface in the applet

Recently, WeChat Mini Program has proposed adjust...

MySQL Full-text Indexing Guide

Full-text indexing requires special query syntax....

Hello dialog box design experience sharing

"What's wrong?" Unless you are accus...

Class in front-end JavaScript

Table of contents 1. Class 1.1 constructor() 1.2 ...

Master-slave synchronization configuration of Mysql database

Table of contents Mysql master-slave synchronizat...

HTML framework_Powernode Java Academy

1. Framework A browser document window can only d...