什么是Typescript
TypeScript 是一種由微軟開(kāi)發(fā)的自由和開(kāi)源的編程語(yǔ)言,它是 JavaScript 的一個(gè)超集,擴(kuò)展了 JavaScript 的語(yǔ)法。作者是安德斯大爺, Delphi、C# 之父(你大爺永遠(yuǎn)是你大爺)。把弱類型語(yǔ)言改成了強(qiáng)類型語(yǔ)言,擁有了靜態(tài)類型安全檢查, IDE 智能提示和追蹤,代碼重構(gòu)簡(jiǎn)單、可讀性強(qiáng)等特點(diǎn)。
現(xiàn)在VUE 也支持了 TypeScript ,面對(duì)安德斯大爺放出的這些大招,果斷用之。
安裝使用
使用 vue-cli 創(chuàng)建項(xiàng)目的時(shí)候 選擇Typescript就行了,
注意下幾個(gè)配置文件

image.png
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
tslint.json
{
"defaultSeverity": "warning",
"extends": [
"tslint:recommended"
],
"linterOptions": {
"exclude": [
"node_modules/**"
]
},
"rules": {
"quotemark": [true, "single"],
"indent": [true, "spaces", 2],
"interface-name": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"no-consecutive-blank-lines": false,
"no-console": false, //允許使用console
"member-access": [true, "no-public"], //禁止指定公共可訪問(wèn)性,因?yàn)檫@是默認(rèn)值
// "noImplicitAny": false, //允許參數(shù)而不聲明其類型
"one-variable-per-declaration": false, //允許在同一聲明語(yǔ)句中使用多個(gè)變量定義
"no-unused-expression": [true, "allow-fast-null-checks"], //允許使用邏輯運(yùn)算符執(zhí)行快速空檢查并執(zhí)行副作用的方法或函數(shù)調(diào)用( 例如e && e.preventDefault())
"curly": [true, "ignore-same-line"],
"arrow-parens": [true, "ban-single-arg-parens"],
"semicolon": [true, "never"],//是否提示不必要的分號(hào)
"trailing-comma": [
true,
{
"multiline": {
"objects": "ignore",
"arrays": "ignore",
"functions": "ignore",
"typeLiterals": "ignore"
},
"esSpecCompliant": true
}
]
}
}
重要的是怎么在項(xiàng)目中使用Typescrit寫法
1:安裝npm install --save vue-property-decorator
此類庫(kù)提供了7個(gè)裝飾器
- @Emit
- @Inject
- @Model
- @Prop
- @Provide
- @Watch
- @Component
實(shí)現(xiàn)生成像原生 JavaScript class 那樣的聲明組件。
下面分別給出實(shí)例解釋其用法:
- @Component
組件聲明
原生寫法
import UploadImage from '@/components/UploadImage'
export default {
name: 'user',
components: { UploadImage },
data() {
return {
name:"張三",
sex: '男'
}
},
methods: {
funcA(params) {},
funcB() {}
}
}
使用Ts中寫法
import UploadImage from '@/components/UploadImage'
import { Component, Vue, Provide } from 'vue-property-decorator'
@Component(name:"user",components:{UploadImage})
export default class user extends Vue{
private name:string="張三"
private sex:string="男"
private funcA(params:any){}
private funcB(){}
}
其中使用 @Component 聲明了 user組件 ,同時(shí)引用 子組件 UploadImage,寫在 Components 參數(shù)中。
- @Prop
屬性聲明 在自定義組建中使用
原生寫法
export default{
name:"upload",
props:{
value:{
type:String,
default:''
}
}
}
在ts中寫法
@Component()
export default class upload extends Vue{
@Prop()
private value:string='';
}
- computed
計(jì)算屬性
這個(gè)很類似于c#中的 屬性概念,屬性值本身可以通過(guò)計(jì)算得出。
原生寫法
computed: {
imageUrl() {
return 'http://xxxx.xxxx.com/' + this.value;//value是定義的一個(gè)字段
}
},
在ts中寫法
get imageUrl(){
return 'http://xxxx.xxxx.com/' + this.value;//value是定義的一個(gè)字段
}
template 中一樣使用{{imageUrl}}
- @watch
用來(lái)監(jiān)測(cè)Vue實(shí)例上的數(shù)據(jù)變動(dòng)
如果對(duì)應(yīng)一個(gè)對(duì)象,鍵是觀察表達(dá)式,值是對(duì)應(yīng)回調(diào),值也可以是方法名,或者是對(duì)象,包含選項(xiàng)。
export default {
name: 'index',
data() {
return {
demo: {
name: ''
},
value: ''
};
},
computed: {
newName() {
return this.demo.name;
}
},
watch: {
newName(val) {
this.value = val;
}
}
};
ts寫法
export default class index extends Vue{
demo:any={name:''};
value:string='';
get newName(){
return this.demo.name;
}
@watch('wnewName')
wnewName(val){
this.value=val;
}
}
- emit
我們知道,父組件是使用 props 傳遞數(shù)據(jù)給子組件,但如果子組件要把數(shù)據(jù)傳遞回去,應(yīng)該怎樣做?那就是自定義事件!
每個(gè) Vue 實(shí)例都實(shí)現(xiàn)了事件接口(Events interface),即:
- 使用 $on(eventName) 監(jiān)聽(tīng)事件
- 使用 $emit(eventName)觸發(fā)事件
Vue.component('counter', {
template: `
<button v-on:click="increment">{{ counter }}</button>`,
data() {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment')
}
},
});
new Vue({
el: '#example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
<div id="example">
<p>{{ total }}</p>
<counter v-on:increment="incrementTotal"></counter>
</div>
子組件自定義了個(gè)事件,然后把這個(gè)事件發(fā)射出去,父組件使用這個(gè)事件