這篇文章主要介紹了Vue2 Vue-cli中使用Typescript的設定介紹,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
Vue作為前端三大框架之一截至到目前在github上以收穫44,873顆星,足以說明其以悄悄成為主流。以下這篇文章主要為大家介紹了Vue2 Vue-cli中使用Typescript的配置的相關資料,需要的朋友可以參考下。
前言
因為最近公司的團隊熱衷於vue框架,新專案想著練練typescript,於是開始了vue ts的踩坑之路...本文意在為和我有一樣想法的伙伴們省去踩坑的時間,下面話不多說了,來一起看看關於Vue2 Vue-cli中利用Typescript需要的配置是什麼吧。
一、初步配置
先安裝官方外掛程式vue-class-component,vue-property-decorator,設定webpack。
webpack設定如下:
修改入口檔案
entry: {
app: './src/main.ts'
}resolve部分:
extensions: ['.js', '.vue', '.json', '.ts', '.tsx']
設定loader
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
}#設定tsconfig.json
{
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"allowJs": true,
"module": "es2015",
"target": "es5",
"moduleResolution": "node",
"experimentalDecorators": true,
"isolatedModules": true,
"lib": [
"dom",
"es5",
"es2015.promise"
],
"sourceMap": true,
"pretty": true
}
}#二、實戰!
搭配好設定只是第一步,在專案裡跑起來才是王道。
在vue檔案的script標籤裡加上lang='ts'
#因為ts-loader不像配過loader的webpack一樣知道vue,html等檔案是什麼東西,你跑起來後會報模組無法解析的錯誤,所以還需要設定.d.ts宣告檔
vue的如下設定
declare module "*.vue" {
import Vue from 'vue';
export default Vue;
}你也可以為其它的非js模組配置.d.ts檔案如html(告訴ts-loader把html理解成字串)
declare module "*.html" {
let template: string;
export default template;
}配置好之後ts就能理解這些模組了
從vue-property-decorator引入需要用到的模組
(一般只用到Component, Vue, Watch, Prop這四個,其它3個沒用到也沒研究,知道的大佬可以解釋下。)
import { Component, Vue, Watch } from 'vue-property-decorator'
#這裡拿之前寫的sidbar的程式碼當個栗子:
#class HoverTopElem {
leaveTop: number = -200
top: number = null
height: number = null
show(e) {
this.top = e.target.getBoundingClientRect().top
this.height = e.target.clientHeight
}
hidden() {
this.top = this.leaveTop
}
}
@Component({
name: 'sidebar',
template: template,
components: {
sidebarItem
}
})
export default class Sidebar extends Vue {
SidebarMenu: any = SidebarMenu
hoverTopElem: HoverTopElem = new HoverTopElem()
activeListItemName: string = null
activeRouteItemRoute: string = null
get _activeRouteItemRoute(): string {
return this.$route.path
}
@Watch('_activeRouteItemRoute', { immediate: true })
onRouteChanged(val: any) {
this.activeRouteItemRoute = val
}
changeList(param) {
this.activeListItemName = param
}
changeRoute(param) {
this.activeRouteItemRoute = param
}
}元資料寫在@Component配置裡,像名字,用到的元件啥的,然後說下之前vue裡用到的各個實例屬性方法在這裡怎麼用:
data: 這個是最常用的,像上面的SidebarMenu(這裡一共聲明了4個),注意這裡聲明的變數一定要賦一個值,沒有就null,不能是undefined,不然這個資料就不是回應的。因此HoverTopElem類別裡的屬性也是要有初始值,不然這些屬性也不是回應的
computed: 這裡就是get函數,注意tsconfig.jsonp不配置"target": "es5"這裡會報錯
prop: vue-property-decorator裡面有Prop模組,也可以在元資料宣告這個prop,然後在類別裡宣告這個變數就可以了,個人推薦第一種
watch: vue-property-decorator裡的Watch模組
methods: 方法像data一樣直接寫在類別裡就可以了(注意不要和周期鉤子同名)
基於casperjs和resemble .js實作一個像素對比服務
在vue專案建立的後初始化首次使用stylus安裝方法的介紹
##
以上是關於Vue2 Vue-cli中使用Typescript的設定介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!