42
头图

Preface

The late Vue3 article actually went through Vue3 as early as March this year. <br/>At the end of last year, TypeScript learned 060e8253f3d0db again, in order to get on the Vue3 car and drive better. <br/>In April of the previous company, the superiors assigned an internal party affairs system to develop. The front-end of this system was developed by myself. The functions and requirements are not too complicated. A B-side system is directly It was developed by Vue3 + TypeScript + Element Plus , and it was developed for two weeks to the final launch. During the period, it also encountered many small pits, many of which are nowhere to be found. I slowly pondered and finally overcome it.

Vue3 + TypeScript Study

Vue 3

One, 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 Vue 3

vue add typescript

2. Attack on Vue3

2. 1 Vue 2 limitations

  1. As components and component dependencies continue to grow, components are difficult to read and maintain
  2. There is no perfect way to solve cross-component code reuse

2.2 How does Vue 3 solve the limitations of Vue 2

  1. Components are difficult to maintain and manage

[Compose function in Vue3, use Compositon Api setUp to solve]

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

Three, Vue3 Composition Ap i

3.1 About Composition Api

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

So you can continue to use Vue2 to write components.

3.2 When to use Composition Api

  1. TypeScript` support
  2. When writing large components, you can use the Composition Api combination function to manage the state well
  3. When reusing code across components

Four, Composition Api essential foundation

4.1 What is setup

setup is another implementation used to configure the component state.

The state defined in the setup, the method must be used in the template return

note:

  • setup method is Lifecycle methods before components , props data Methods Computed
  • At the same time, setup cannot be accessed in this

4.2 ref Create responsive variables

In Vue2 , we define a reactive variable that can be directly data and use the variable in the template. If you are using composition api , we have in setup use ref to create a responsive variable, and it will have to return in order to use the page.

use

    1. Introduce ref import { ref } from 'vue'
    1. Initial variable const name = ref('Specify default value')
    1. The return variable return { name } can also return to the method in return
    1. To setup , it cannot be obtained directly through the variable name. must obtain the object and value through the variable name.value

Such benefits

  • Good state management, you can divide several setup state management, and finally import all of them in one file and use them.
<template>
    <div>
        <h1>{{title}}</h1>
    </div>
</template>

<script>
import {ref,defineComponent} from 'vue'
export default defineComponent({
    setup () {
        // 定义响应式变量
        const title = ref('前端自学社区')
        
          // 访问该变量
        console.log(title.value)
        // 返回变量
        return {title}
    }
})
</script>

4.3 life cycle

The Composition Api lifecycle hook has the same name as the Vue 2 option lifecycle hook, but when using the combined API , the prefix is on , onMounted`

sd

There are two mounted life hooks in the following code. Guess which one will be executed first?

setup will be executed first
    setup () {
        // 定义响应式变量
        const title = ref('前端自学社区')
        console.log(title)
        // 返回变量
        function getTitle(){
            console.log(title.value)
        }
        // 页面在加载
        onMounted(getTitle)
        return {title}
    },
    mounted() {
        console.log('测试 mounted 执行顺序')
    },

4.4 watch

Use watch responsive change in setup

  • Introduce watch, import { watch } from 'vue'
  • Use watch directly, watch accepts 3 parameters

    1. Responsive reference or getter function to listen for updates
    2. A callback is used to do the updated operation
    3. Optional configuration items
import {wathc} from 'vue'

// 定义响应式变量
const num = ref(0)
// 更新响应式变量
function  changeNum(){
            num.value++
}

// wathc 监听响应式变量
watch(
 num,(newValue, oldValue) => {
 console.log(`newValue为:${newValue},--------oldValue为:${oldValue}`)
   }
 )

4.5 computed

It is also the vue introduced, computed function returns as a computed getters callback class output the first parameter passed a read-only of responsive reference . In order to access the newly created calculated variables of value , we need to use as ref as use .value Property.

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

import {ref,computed} from 'vue';

const num = ref(0)

//更新num
function  changeNum(){
   num.value++
 }
//监听num变化
 const nums = computed(() =>{
  return num.value * 3
 })

Five, setup

5.1 Accept two parameters

props : The properties passed by the parent component. The props in the setup` function are responsive. It will be updated as the data is updated. ES6 deconstruction cannot be used because it will not be able to make props responsive.

context : It is an ordinary object, which exposes 3 components. property

  1. Attribute
  2. Slot
  3. trigger event

context is not responsive, so you can use ES6 deconstruction to write it simply.

   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 setup

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

  • data
  • computed
  • methods

Six, life cycle

When setup , the prefix must be added with on .

Option APIHook inside setup
beforeCreate
created
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeUnmountonBeforeUnmount
unmountedonUnmounted
errorCapturedonErrorCaptured
renderTrackedonRenderTracked
renderTriggeredonRenderTriggered

Seven, pass values between components

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

setup in 060e8253f4b9f2, it must be imported and used vue

When using Provide , it is generally set to be responsive update. In this case, the parent component changes, the child components, and the descendant components are also updated.

How to set it as a responsive update?

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

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("我父组件");
    const info = reactive({
      id: 23,
      message: "前端自学社区",
    });
    function changeProvide(){
      info.message = '测试'
    }
    provide('father',father)
    provide('info',info)
    return {changeProvide};
    }
    
})
</script>

Subassembly

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

Eight, use TypeScirpt skills in Vue

8.1 Interface constraint constraint attributes

Using TypeScirpt , type assertion + interface perfectly constrain the attributes
interface
分页查询 字段属性类型验证
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:'测试',
                age: 2
            } as queryType
        }
    },

8.2 Use of components to define defineComponent

This way TypeScript correctly infers the type in the Vue
import { defineComponent } from 'vue'

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

8.3 Type declaration reactive

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}

At last

If there is an error in the article, you are welcome to correct it in the comment area. If it is helpful to you, please like and follow~~~


程序员海军
942 声望7k 粉丝