Skip to content
本页目录

1个项目学会TypeScript核心基础语法

b站up:技术蛋老师

效果如图

image-20230407221802036

功能

  • 点击随机1只喵,表格出现一行
    • 会请求到随机的猫猫图片
  • 点击删除表格就会取消,会取消一行
    • 删除一行

typescript与JavaScript的开发的区别

其实ts和js逻辑上没有差别,就是加个类型。

但是ts会比js文件多一步编译,但是可以用webpack进行自动打包typescript,就相当于和js体验差不多

如何设置webpack进行自动打包请参考下一篇文章

步骤

那么就首先写html和style 之后再写js 然后给js设置类型就变成ts

代码编写

1.编写html和css

写一个button和table

html
  <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="https://cdn2.thecatapi.com/images/3p4.gif" /></td>
				<td>高度xx</td>
				<td>宽度xx</td>
				<td>地址xx</td>
				<td><a href="javascript:;">X</a></td>
			</tr>
		</tbody>
	</table>

2.编写style(非重点)

Click me to view the code
css
      body {
      width: 900px;
      height: 800px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    button {
      font-size: 1.5rem;
      color: rgb(7, 75, 99);
      width: 200px;
      margin: 10px;
    }

    table {
      text-align: center;
    }

    th, td {
      border: 1px solid rgb(118, 156, 148);
      padding: 5px;
    }

    a {
      text-decoration: none;
      color: red;
      font-weight: bolder;
    }

    img {
      height: 30px;
      width: 30px;
    }

    @keyframes changing {
      from {
          border-style: solid;
      }
      to {
          border-style: dotted;
          border-color: red;
      }
    }

    .remind {
      border-style: solid;
      animation-name: changing;
      animation-duration: 1s;
      animation-timing-function: linear;
      animation-iteration-count: infinite;
    }

    .green {
      background-color: rgb(106, 181, 118);
    }

2.编写typescript

typescript的写法

typescript
let a: string = '3'
console.log(a)

分析元素绑定的对象

typescript
const button: HTMLButtonElement|null = document.querySelector('button')
button?.addEventListener<'click'>('click',getData)

请求的数据格式

typescript
interface CatType{
  id: string
  url: string
  height: number
  width: number 
}

class Cat implements CatType{
  id: string
  url: string
  height: number
  width: number 
  
  constructor(id:string,url:string,height:number,width:number){
    this.id = id
    this.url = url
    this.height = height
    this.width = width
  }
}

请求方法

typescript
const url: string = 'https://api.thecatapi.com/v1/images/search'
// 请求接口的通用函数
async function getJSON<T>(url:string):Promise<T> {
  const response: Response = await fetch(url)
  const json: Promise<T> = await response.json()
  return json
}
// 请求处理
async function getData(){
  try{
    const json: CatType[] = await getJSON<CatType[]>(url)
    const data: CatType = json[0]
    WebDisplay.addData(data)	// 此为在表格添加一行的操作
  }
  catch(error: Error|unknown){
    let message: string 
    if(error instanceof Error){
      message = error.message
    }else{
      message = String(error)
    }
    console.log(message)
  }
}

此为在表格添加一行的操作

typescript
const tableBody: HTMLTableElement|null = document.querySelector('#table-body')

class WebDisplay{
    // 添加操作
  public static addData(data:CatType): void{
    const cat = new Cat(data.id,data.url,data.height,data.width)
    const tableRow: HTMLTableRowElement = document.createElement('tr')
    tableRow.innerHTML = `
        <td>${cat.id}</td>
        <td><img src="${cat.url}" /></td>
        <td>${cat.height.toString()}</td>
        <td>${cat.width.toString()}</td>
        <td>${cat.url}</td>
        <td><a href="javascript:;">X</a></td>
    `
    tableBody?.appendChild(tableRow)
  }
   // 删除操作
  public static deleteData(deleteButton: HTMLAnchorElement): void {
    const td = deleteButton.parentElement as HTMLTableCellElement
    const tr = td.parentElement as HTMLTableRowElement
    tr.remove()
  }
}

删除操作

typescript
tableBody?.addEventListener('click',(ev: MouseEvent)=>{
  console.log("ev.target",ev)
  let target = ev.target as HTMLElement
  if(target?.nodeName === 'A'){
    WebDisplay.deleteData(<HTMLAnchorElement>ev.target)
  }
})