TypeScript是一個js的超級,提供了類型系統和es6的支持,它是由微軟開發,第一個版本發佈於2012年10月,經屢次更新,現已成爲前端社區中不可忽視的力量,而且已經在微軟內部普遍應用,google的angular2也使用了TypeScript的開發語言,這也就是咱們爲何學習ts的背景。html
咱們經常使用的vue框架也支持了使用typeScript開發,今天咱們就來學習一下如何使用vue-cli3+typeScript開發一個簡單項目,最近在研究騰訊的ai接口,完成一個簡單的demo,話很少少,上代碼前端
一、安裝vue-cli3,檢查版本,建立項目,已經全局安裝過vue-cli3的直接建立項目便可,跟以前同樣vue
npm install -g @vue/cli vue --version vue create my-ts-ai
二、須要注意的是第一次使用ts的,能夠選擇Manually select feature
來自由選擇功能,經常使用的有vuex、vue-router、CSS Pre-processors等,咱們必定要把typescript勾上,就能夠回車進入下一步了。PS:勾選的操做是按空格鍵。
須要注意,選擇格式化檢查的,須要選擇TSlint,不然寫ts會標紅報錯
;node
三、建立成功以後,執行啓動命令:npm run serve;啓動以後就能夠訪問本地項目、用ts編寫代碼了ios
這是一個涵蓋了vue的一些對象的集合,咱們能夠從這裏取一些東西出來es6
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
取出來的這幾個屬性,分別是 組件定義Component
,父組件傳遞過來的參數Prop
,原始vue對象Vue
,數據監聽對象Watch
。還包括這裏沒有列舉出來的Model
,Emit
,Inject
,Provide
,能夠本身嘗試下。
咱們看一下經常使用的屬性prop、watch通常寫法
prop;@Prop() private msg!: string;
watch:算法
// watch @Watch('active') private chageActive(newVal: string, oldVal: string) { console.log(`change txt: ${oldVal} to ${newVal}`); } @Watch('sticker') private chageSticker(newVal: string, oldVal: string) { console.log(`change txt: ${oldVal} to ${newVal}`); }
data:vue-router
// data private num: number = 0; private appId: number = 2140682408; private appKay: string = '3gP0QJTqC3j8qP6M'; private imgBase64: string = ''; private effectImg: string = '';
methods:vuex
private choose(id: number, index: number) { this.sticker = id; this.active = index; } private postData(url: string, params: object) { const self: IParams = this; axios.post(url, qs.stringify(params), { headers: {'Content-Type': 'application/x-www-form-urlencoded'}, }).then( (response) => { console.log(response.data); if (response.data.ret === 0) { self.effectImg = 'data:image/jpeg;base64,' + response.data.data.image; } }).catch((error) => { console.log(error); }); }
computed:vue-cli
// computed get getMsg() { return this.msg + '11111'; } get testTxt() { return this.$store.state.testTxt; }
在store裏寫法基本不變只要遵循ts的規則便可;
主要是說一下使用的時候的注意事項,話很少說直接上代碼
引如
// 使用vuex import { State, Getter, Action, Mutation, namespace, } from 'vuex-class'; const userModule = namespace('user')
聲明
@State('testNum') public testNum!: any; @Action('UPDATA_CHANGE_LOGIN') public UPDATA_CHANGE_LOGIN!: Function; @Mutation('CHANGE_LOGIN') public CHANGE_LOGIN!: Function; @userModule.State('firstName') public firstName!: string; @userModule.State('lastName') public lastName!: string; @userModule.Mutation('UPDATE_FIRST_NAME') public UPDATE_FIRST_NAME!: Function
而後像之前那樣使用便可;
以上是我寫的使用typeScript、vue-cli3框架編寫的demo的重點;
下面主要說一下前端使用騰訊ai接口作一些效果;
關於註冊、建立應用這些能夠本身在網站嘗試
前端是沒有權限直接調用接口鑑權的,由於有跨域問題,通常須要後臺配合,因此如下這些代碼可使用nodejs開發;
由於是在vue框架下作的開發,vue幫助咱們作了服務器代理,因此咱們能夠在本地配置代理服務器,看下效果,同時瞭解基本的步驟,後續使用nodejs作接口鑑權;話很少少上代碼
主要是簽名算法,遵循騰訊的簽名算法規則 詳見https://ai.qq.com/doc/auth.shtml
簽名算法步驟
private postPurikura() { // 調用大頭貼的接口,參數詳見騰訊開放平臺apihttps://ai.qq.com/doc/facesticker.shtml const params: IParams = { app_id: this.appId, time_stamp: parseInt((new Date().getTime() / 1000).toString(), 10), nonce_str: Math.random().toString().substr(3, 8) + Date.now().toString(36), image: this.imgBase64, sticker: this.sticker, }; const sign = this.getSign(params, this.appKay); // 簽名算法,遵循騰訊的簽名算法規則 詳見https://ai.qq.com/doc/auth.shtml params.sign = sign; this.postData(apis.facesticker, params); } private getSign(params: any, appkey: string) { const sortArr = Object.keys(params).sort((x: string, y: string): number => { return x.localeCompare(y, 'zh-Hans-CN', { sensitivity: 'accent' }); }); const newParams: IParams = {}; sortArr.forEach((ele: string) => { newParams[ele] = params[ele]; });// 請求參數對按key進行**字典升序**排序 console.log(newParams); let url: string = ''; Object.keys(newParams).forEach((key: string, i) => { if (newParams[key] !== '') { url += key + '=' + encodeURIComponent(newParams[key]) + '&'; } }); url += 'app_key=' + appkey; // 列表N中的參數對按**URL鍵值對的格式**拼接成字符串,並將應用密鑰以app\_key爲鍵名,組成URL鍵值拼接到字符串T末尾,獲得**字符串S**(如:key1=value1&key2=value2&app\_key=密鑰) const md5url = md5(url); // 對字符串S進行MD5運算 const sign = md5url.toUpperCase(); // 的**MD5值全部字符轉換成大寫**,獲得接口**請求籤名** console.log(sign); return sign; }
一、對象要建立接口;直接定義類型爲object,必須是已經肯定的屬性和值,若是新加屬性,則會標紅提示沒有這個屬性值;建立接口的方式以下
interface IParams { [x: string]: any } // 使用的時候,就能夠給reader隨意增長屬性 `const reader: IParams = new FileReader();`
二、parseInt
要傳2個參數,否則會報Missing radix parameter,這個意思是缺乏一個基數根parseInt(string, radix)
函數的,這個函數一共須要兩個參數:
三、控制檯報錯 Calls to 'console.log' are not allowed.不被容許寫入console,要在tslint.json中的rules中加入 "no-console": false。方便測試
四、注意和js作區分,一句代碼結束要加;,對象的最後一個屬性要加,
五、若是VSCode編輯器有警告提示,好比: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
能夠把工做區其餘的項目移除,或者把本項目拖動到工做區的首位,或者在把本項目的tsconfig.json複製到工做區首位的項目的根目錄下,重啓編輯器,有比較大的機率能夠解決警告提示。