在vue中使用typescript - 使用篇

基本使用

// page頁(yè)面======================================================================
import { Component, Vue } from 'vue-property-decorator'
import NavBar from '@/components/NavBar.vue'
// 使用組件
@Component({
  components: {
    NavBar
  }
})
// 創(chuàng)建頁(yè)面組件
export default class App extends Vue {
  
}

// 接口interface 文件=============================================================
export interface MainButtonType {
  id: number;
  icon: string | any;
  name: string
}


// 組件===========================================================================
<template>
  <div class="home">
    <swiper :options="swiperOption" class="swiper-wrap">
      <swiper-slide v-for="(slide, index) in swiperData" :key="index">
        <img :src="slide.imgUrl" />
      </swiper-slide>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>

    <div class="button-wrap">
      <main-button :ButtonData="ButtonData" @buttonClick="handleButtonClick"/>
    </div>

    <div class="exp">
      <filter-component/>
    </div>
  </div>
</template>

import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import { Component, Prop, Vue } from 'vue-property-decorator'
import MainButton from '@/components/MainButton.vue'
import FilterComponent from '@/components/FilterComponent.vue'
import { MainButtonType } from '@/types'

@Component({
  components: {
    swiper,
    swiperSlide,
    MainButton,
    FilterComponent
  }
})
export default class Home extends Vue {
  // 定義data數(shù)據(jù)
  private swiperData: any[] = [
    {
      id: 0,
      imgUrl: require('../assets/banner.png')
    }
  ]
  private swiperOption: object = {}
  // 使用interface接口定義類(lèi)型 => MainButtonType
  private ButtonData: MainButtonType[] = [
    {
      id: 0,
      icon: require('../assets/travel_application.png'),
      name: '出差申請(qǐng)'
    },
    {
      id: 1,
      icon: require('../assets/flight.png'),
      name: '機(jī)票'
    }
  ]
  // 接口子組件的emit的函數(shù)
  private handleButtonClick(id: number): void {
    console.log('id:', id)
  }
}

// MainButton 組件中(子組件)===============================================================
import { Component, Prop, Vue, Emit, Watch } from 'vue-property-decorator'
import { MainButtonType } from '@/types'

@Component
export default class MainButton extends Vue {
  // props
  @Prop({default: []}) ButtonData!: MainButtonType[]
  // 生命周期
  created(): void {
    console.log('created')
  }
  // watch
  @Watch('ButtonData', {deep: true, immediate: true})
  ButtonDataWatch(val: MainButtonType[]):void {
    console.log(123, val)
  }
  // emit
  @Emit('buttonClick')
  private handleItemClick(id: number): void {
    // 函數(shù)的參數(shù)值即是emit的payload
  }
}

// filterComponent組件:filters和computed示例 (子組件)==================================================================
<template>
  <div class="filter-wrap">
    <div>filters示例:{{exp | formatNum}}</div>
    <br/>
    <div>computed示例:{{computedNum}}</div>
  </div>
</template>

import { Component, Vue } from 'vue-property-decorator'

@Component({
  // filters
  filters: {
    formatNum(val: number): string {
      if (!val && val !== 0) return ''
      return val.toFixed(2)
    }
  }
})
export default class FilterComponent extends Vue {
  private exp: number = 12.346546754
  // computed
  get computedNum(): number {
    return this.exp * 1000
  }
}

在vuex中使用

  1. 注: typescript目前對(duì)vuex的支持還不完善庐船,需要引入 vuex-class 包來(lái)支持
  2. vuex-class 提供了State, Getter, Action, Mutation, nam-espace 這幾個(gè)裝飾器
  3. 示例
// vuex中蔓彩, 以state為例
// 1. 定義接口
export interface USERINFO {
  userId: number;
  userName: string;
  avatar: string
}

export default interface STATE {
  userInfo: USERINFO;
}

// 2. state.js使用接口
import STATE from './stateType.js';
const state: STATE = {
  userInfo: {
    userId: 0,
    userName: '',
    avatar: '',
  }
};
export default state;


// 組件中使用
import Vue from 'vue'
import Component from 'vue-class-component'
import {
  State,
  Getter,
  Action,
  Mutation,
  namespace
} from 'vuex-class'

const someModule = namespace('path/to/module')

@Component
export class MyComp extends Vue {
  @State('foo') stateFoo
  @State(state => state.bar) stateBar
  @Getter('foo') getterFoo
  @Action('foo') actionFoo
  @Mutation('foo') mutationFoo
  @someModule.Getter('foo') moduleGetterFoo

  @State foo
  @Getter bar
  @Action baz
  @Mutation qux

  created () {
    this.stateFoo // -> store.state.foo
    this.stateBar // -> store.state.bar
    this.getterFoo // -> store.getters.foo
    this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
    this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
    this.moduleGetterFoo // -> store.getters['path/to/module/foo']
  }
}

注意事項(xiàng)

  1. vue-property-decoratorvue-class-component 的區(qū)別
  • vue-class-component 是 vue 官方出的
  • vue-property-decorator 是社區(qū)出的
  • 其中vue-class-component 提供了 vue component 等等
  • vue-property-decorator 深度依賴了 vue-class-component 拓展出了很多操作符@Prop @Emit @Inject等等 可以說(shuō)是vue-class-component的一個(gè)超集
  • 正常開(kāi)發(fā)的時(shí)候 你只需要使用vue-property-decorator中提供的操作符即可 不用再?gòu)?code>vue-class-componen引入vue component
  1. 引入第三方包報(bào)錯(cuò)
  • 現(xiàn)象: Could not find a declaration file for module 'vue-awesome-swiper'
    e7e1f5f462d88e9d304441f1e1cb962.png
  • 原因: 插件文件可能不是.ts文件而是.js文件
  • 解決方案一: 安裝對(duì)應(yīng)的ts模塊
  • 解決方案二: 配置 shims-vue-d.ts 文件(推薦)
      import Vue from "vue"
      import VueRouter, { Route } from "vue-router"
    
      declare module '*.vue' {
        export default Vue
      }
    
      declare module "vue/types/vue" {
        interface Vue {
          $router: VueRouter; // 這表示this下有這個(gè)東西
          $route: Route;
          $https: any;
          $urls: any;
          $Message: any;
          $Modal: any;
        }
      }
      // 以swiper為例,在此添加聲明
      declare module 'vue-awesome-swiper'
    
  • 解決方案三: 配置 tsconfig.json 文件
      {
        "compilerOptions": {
          ...
          "noImplicitAny": false,   // 忽略引入類(lèi)型檢查
          ......
        }
      }
    
  1. 聲明全局變量
  • 添加shime-global.d.ts文件闲询,與main.ts同級(jí)
// 聲明全局的 window 涤浇,不然使用 window.XX 時(shí)會(huì)報(bào)錯(cuò)
// declare var window: Window;
declare var document: Document;
declare var THREE: any;

// interface THREE extends Window {}

// element-ui
declare module "element-ui/lib/transitions/collapse-transition";
declare module "element-ui";
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末宙拉,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子懦傍,更是在濱河造成了極大的恐慌雹舀,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粗俱,死亡現(xiàn)場(chǎng)離奇詭異说榆,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)寸认,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)签财,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人偏塞,你說(shuō)我怎么就攤上這事唱蒸。” “怎么了灸叼?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵神汹,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我古今,道長(zhǎng)邻耕,這世上最難降的妖魔是什么氨淌? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮琼腔,結(jié)果婚禮上富弦,老公的妹妹穿的比我還像新娘盗蟆。我一直安慰自己虫埂,他們只是感情好贷盲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著立磁,像睡著了一般呈队。 火紅的嫁衣襯著肌膚如雪剥槐。 梳的紋絲不亂的頭發(fā)上唱歧,一...
    開(kāi)封第一講書(shū)人閱讀 51,679評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼颅崩。 笑死几于,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的沿后。 我是一名探鬼主播沿彭,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼尖滚!你這毒婦竟也來(lái)了喉刘?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤漆弄,失蹤者是張志新(化名)和其女友劉穎睦裳,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體撼唾,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡廉邑,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了倒谷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蛛蒙。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖渤愁,靈堂內(nèi)的尸體忽然破棺而出牵祟,到底是詐尸還是另有隱情,我是刑警寧澤抖格,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布课舍,位于F島的核電站,受9級(jí)特大地震影響他挎,放射性物質(zhì)發(fā)生泄漏筝尾。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一办桨、第九天 我趴在偏房一處隱蔽的房頂上張望筹淫。 院中可真熱鬧,春花似錦呢撞、人聲如沸损姜。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)摧阅。三九已至,卻和暖如春绷蹲,著一層夾襖步出監(jiān)牢的瞬間棒卷,已是汗流浹背顾孽。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留比规,地道東北人若厚。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像蜒什,于是被迫代替她去往敵國(guó)和親测秸。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容