一、新專案建立
1.1 使用vue-cli建立專案
專案程式碼變化
1.2 啟動專案yarn serve
二、TS在vue中的使用
2.1 型別註釋
- 新建自定義型別:
src/models/people.ts
interface People {
id: number;
name: string;
age: number
}
export default People複製程式碼
- 在使用中使用
<ul>
<li v-for="people in people" :key="people.id">
{{people.name}}
<span class="tag">年齡:{{people.age}}</span>
</li>
</ul>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import People from "@/models/people";
//裝飾器
@Component
export default class HelloWorld extends Vue {
//宣告屬性為data
people: People[] = [{ id: 1, name: "子秋", age: 18 }];
}
</script>
複製程式碼
2.2 運算元據addPeople
- 新增新人
<div>
<input type="text" placeholder="輸入名稱" @keyup.enter="addPeople" />
</div>複製程式碼
- 新增新人方法(斷言as)
//方法可以直接作為事件回撥函式
addPeople(event: KeyboardEvent) {
//斷言event是HTMLInputElement
const input = event.target as HTMLInputElement;
//不可直接使用event.target.value
this.people.push({
id: this.people.length + 1,
name: input.value,
age: 18
});
input.value = "";//清空input
}
複製程式碼
2.3 計算屬性get
<!-- 總數的統計 -->
<li>人數統計:{{total}}</li>
//存取器:計算屬性
get total() {
return this.people.length;
}
複製程式碼
2.4 資料獲取
- 新增資料檔案
vue.config.js
,重啟專案yarn serve
module.exports = {
devServer: {
before(app) {
app.get('/api/list', (req, res) => {
res.json([
{ id: 1, name: '碧落', age: 19 },
{ id: 2, name: '孟婆', age: 27 },
{ id: 3, name: '秋韻', age: 17 },
])
})
}
}
}複製程式碼
- 安裝axios,新建
src/api/people.ts
,關鍵<People[]>
import axios from 'axios'
import People from '@/models/people'
//不需要約束函式返回值,是由於會進行推斷
export function getPeople() {
//函式返回值People型別
return axios.get<People[]>('/api/list')
}複製程式碼
- 生命週期呼叫
import { getPeople } from "@/api/people.ts";
//生命週期鉤子
mounted() {
//資料獲取
getPeople().then(res => {
this.people = res.data;
});
}
複製程式碼
2.5 構造器$Emit
import { Emit } from "vue-property-decorator"
//HelloWorld.vue
//方法可以直接作為事件回撥函式
@Emit()
addPeople(event: KeyboardEvent) {
//斷言event是HTMLInputElement
const input = event.target as HTMLInputElement;
//不可直接使用event.target.value
const people = {
id: this.people.length + 1,
name: input.value,
age: 18
};
this.people.push(people);
input.value = ""; //清空input
return people;
}
//父級
<div id="app">
<HelloWorld msg="歡迎來到古風秋林" @add-people="onAddPeople" />
</div>
export default class App extends Vue {
onAddPeople(p: People) {
alert("新增了" + p.name);
}
}
複製程式碼