Vue3+ts gets backend data

1. The data table data to be obtained
is simply a table data demonstration, named user table.

id name sno
1 You 0001
2 HuZi 0002
2. Front-end processing
Vue3 has changed a lot compared to Vue2. If ts is used instead of js, the difference is magnified. The following demonstrates how vue3+ts receives data from the backend. Data list information and display it
1) Create a type interface (entity) that receives the user table

Create a base.ts file and write the interface in it. Generally, this interface will be specifically encapsulated in a ts file. This file will specifically store the interface corresponding to each data table; back to the topic, create the user interface, the code is as follows:

export interface UserData{//用户表对应的接口
    id:number
    name:string
    sno:string
}
export interface SearchModelData{//如果要进行分页,根据用户名搜索数据,可以把相应的变量封装在一起,不用一个一个变量去在vue界面定义,这里直接创建一个整合在一起的接口
    currentPage: number
    pageSize: number
    userName: string
}

The data in the interface should correspond to the user table, and the type should also correspond. This is the characteristic of ts. Each variable requires a corresponding type. Of course, for data of unknown type, the any type is provided, which means any; such as name: Any can be

2) The vue interface starts to call and obtain

It should be noted that the encapsulated objects and variables of vue3 are different from those of vue2. In addition, this article uses ts, so the gap will be larger. The encapsulation is as follows. Import the
tools you need to use and create the objects.

<script lang="ts" setup>//这一句很重要,ts表示使用ts语法,setup是一种自动注册机制,将变量和方法自动注册,elementPlus组件就可调用了;有了这些,就用再想vue2+js中那样定义data、methods等
import {toRefs, reactive} from "vue";
import {UserData,SearchModelData} from "@/base";//导入接口
import {getUserListAPI} from "@/api/userApi";//访问后端的request方法,上篇文章讲过如何定义及使用
//定义对象
const state = reactive({
    userInfo:[] as UserData[],//因为后端传来的是List数组,而不是一条数据,这种就是定义成对象数组形式
    total: 0,//如果需要分页,可以定义一个总页数
    searchModel:{
        currentPage: 1,
        pageSize: 10,
        userName: ""
    } as SearchModelData,//上面userInfo是定义对象数组,这个就是定义一个对象的方法,注意差别
})
//封装数据,这个是为了函数以及vue界面的那些组件(v-model)可以取到上面state中定义的对象及变量,封装之后就可以使用state.total这种形式调用了
const {
  userInfo,
  searchModel,
  total,
}=toRefs(state) 
//获取后端数据
function getUserList(){
  getUserListAPI(state.searchModel).then((res:any)=>{
    console.log(res)
    state.userInfo=res.userList
    state.total=res.total
  })
}

It should be noted that when using the front-end component element in vue3, you need to use elementPlus instead of elementUI. The latter is for vue2 and is not very compatible with vue3.

Guess you like

Origin blog.csdn.net/weixin_44821114/article/details/133324176