概述:
template 和 style 跟以前的寫法保持一致,只有 script 的變化
Vue三個TS封裝庫
vue-class-component
vue-class-component 對 Vue 組件進行了一層封裝,讓 Vue 組件語法在結合了 TypeScript 語法之后更加扁平化
vue-property-decorator
vue-property-decorator 是在 vue-class-component 上增強了更多的結合 Vue 特性的裝飾器,新增了這 7 個裝飾器
vuex-class
1.通過vue-cli3生成項目
vue create xxx
1
注:安裝時選擇TypeScript之后,回自動安裝vue-class-component,vue-property-decorator,具體見package.json文件
vue-cli3腳手架生成項目目錄說明
│ .browserslistrc
│ .gitignore
│ .postcssrc.js // postcss 配置
│ babel.config.js
│ package.json // 依賴
│ README.md // 項目 readme
│ tsconfig.json // ts 配置
│ tslint.json // tslint 配置
│ vue.config.js // webpack 配置(~自己新建~)
│ yarn.lock
│
├─public // 靜態頁面
│ │—favicon.ico
│ │—index.html
│
├─src // 主目錄
│ ├─assets // 靜態資源
│ │ logo.png
│ │
│ ├─components
│ │ HelloWorld.vue
│ │
│ │─views // 頁面
│ │ About.vue
│ │ Home.vue
│ │
│ │ App.vue // 頁面主入口
│ │
│ │ main.ts // 腳本主入口
│ │
│ ├─router // 路由配置
│ │ index.ts
│ │
│ │ registerServiceWorker.ts // PWA 配置
│ │
│ │ shims-tsx.d.ts
│ │ shims-vue.d.ts
│ │
│ ├─filters // 過濾(~自己新建~)
│ ├─lib // 全局插件(~自己新建~)
│ │
│ │
│ ├─store // vuex 配置
│ │ index.ts
│ │
│ ├─typings // 全局注入(~自己新建~)
│ │
│ ├─utils // 工具方法(axios封裝,全局方法等)(~自己新建~)
│
│
└─tests // 測試用例
├─e2e
│ ├─plugins
│ │ index.js
│ │
│ ├─specs
│ │ test.js
│ │
│ └─support
│ commands.js
│ index.js
│
└─unit
HelloWorld.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
shims-vue.d.ts文件說明
注:由於 TypeScript 默認並不支持 *.vue 后綴的文件,所以在 vue 項目中引入的時候需要創建一個shims-vue.d.ts 文件,放在項目項目對應使用目錄下,例如 src/shims-vue.d.ts,用來支持*.vue 后綴的文件;
2.tslint配置 “rules”: {…}
// 關閉console
"no-console": [true, "log", "dir", "table"]
// tslint的函數前后空格:
"space-before-function-paren": ["error", {
"anonymous": "always",
"named": "always",
"asyncArrow": "always"
}]
// tslint分號的配置:
"semicolon": [true, "never"]
1
2
3
4
5
6
7
8
9
10
11
12
13
TSlint其他配置
3.路由改造(全局路由攔截,用戶登陸驗證等),修改App.vue文件,如下
// App.vue 文件
import router from '@/router/index'
router.beforeEach((to: any, from: any, next: any) => {
if (to.name === 'login') {
next({name: 'home/index'})
} else {
next()
}
})
1
2
3
4
5
6
7
8
9
10
例如:
4. *.vue文件改造
注:template 和 style 跟以前的寫法保持一致,只有 script 的變化
5.父組件傳值給子組件(使用vue-property-decorator裝飾器 @Prop)
6.子組件傳值給父組件(使用vue-property-decorator裝飾器 @Emit)
注:@Emit其他寫法
7.偵聽器watch(使用vue-property-decorator裝飾器 @Watch)
注:handler,immediate和deep
如下寫的函數其實就是在寫這個handler方法里面的;
watch: {
firstName (val) {
this.fullName = val + ' ' + this.lastName
}
}
1
2
3
4
5
當值第一次綁定的時候,不會執行監聽函數,只有值發生改變才會執行。如果我們需要在最初綁定值的時候也執行函數,則就需要用到immediate屬性為true。
當需要監聽一個對象的改變時,普通的watch方法無法監聽到對象內部屬性的改變,只有data中的數據才能夠監聽到變化,此時就需要deep屬性對對象進行深度監聽。
————————————————
版權聲明:本文為CSDN博主「非為000」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_30669833/article/details/90487700