跳至主要內容
typeScript中使用axios

项目一

根据名称获取动漫列表

1,定义api.type.ts (定义后台接口返回的类型)


interface ApiFormat<T> {
  /** 状态码 */
  code: number
  /** 状态文字 */
  message: string
  /** 数据 */
  data: T
}

export type Search = ApiFormat<{
  /** 当前返回页数 */
  pageindex: number
  /** 总页数 */
  pagetotal: number
  /** 动漫列表 */
  results: {
    /** 分类列表 */
    category: string
    /** 封面 */
    cover: string
    /** 首发时间 */
    date: string
    /** 介绍 */
    description: string
    /** 动漫id */
    id: string
    /** 动漫状态(更新、完结...) */
    season: string
    /** 动漫名称 */
    title: string
  }[]
}>
    

qianxun大约 1 分钟vue知识点必会vue中的 TypeScript
typeScript项目实战

一,利用typeScript实现新增,删除一行数据

这里基本涵盖了typeScript在项目中的实战用法

1,html部分

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" href="./style.css" />
	<title>蛋老喵</title>
</head>
<body>
	<button class="remind">随机1只喵</button>
	<table>
		<thead>
			<tr>
				<th>图片id</th>
				<th>图片预览</th>
				<th>图片高度</th>
				<th>图片宽度</th>
				<th>图片地址</th>
				<th>删除图片</th>
			</tr>
		</thead>
		<tbody id="table-body">
			<tr>
				<td>idxxx</td>
				<td><img src="./example.jpeg" /></td>
				<td>高度xx</td>
				<td>宽度xx</td>
				<td>地址xx</td>
				<td><a href="#">X</a></td>
			</tr>
		</tbody>
	</table>
	<script src="./script.js"></script>
</body>
</html>


qianxun大约 1 分钟vue知识点必会vue中的 TypeScript
typeScript在vue项目中常见用法

一,模板中的 TypeScript

在使用了 <script lang="ts"> 或 <script setup lang="ts"> 后,<template> 在绑定表达式中也支持 TypeScript。

<script setup lang="ts">
let x: string | number = 1
</script>

<template>
  <!-- 出错,因为 x 可能是字符串 -->
  {{ x.toFixed(2) }}
</template>

qianxun大约 2 分钟vue知识点必会vue中的 TypeScript
typeScript中的泛型

一,泛型

泛型就是通过给类型传参,得到一个更加通用的类型,就像给函数传参一样。 如下我们得到一个通用的泛型类型 T1,通过传参,可以得到 T2 类型 string[]、T3 类型 number[]; T 是变量,我们可以用任意其他变量名代替他。


type T1<T> = T[]

type T2 = T1<string> // string[]

type T3 = T1<number> // number[]


qianxun大约 2 分钟vue知识点必会vue中的 TypeScript
typeScript在vue3中的实战

ts在表单中的应用

      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="70px">
        <h2>后台管理系统</h2>
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
        </el-form-item>

        <el-form-item label="密码:" prop="password">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button class="login-btn" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
          <el-button class="login-btn" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>

qianxun大约 2 分钟vue知识点必会vue中的 TypeScript