TypeScript+Vue
Vue官方TypeScript支持文檔
初始化項目
使用@vue/cli創(chuàng)建模版項目(啥是@vue/cli)
具體操作自行百度
提示:
@vue/cli腳手架默認生成的項目是零webpack配置,但是可以支持自定義webpack配置。只需在根目錄下新建vue.config.js配置文件,這個文件會被@vue/cli-service自動加載。
vue.config.js基礎(chǔ)配置模版:
const path = require("path"); const sourceMap = process.env.NODE_ENV === "development";module.exports = {// 基本路徑publicPath: "./",// 輸出文件目錄outputDir: "dist",// eslint-loader(作用:對編譯前的ES6語法進行檢查) 是否在保存的時候檢查lintOnSave: false,// webpack配置chainWebpack: () => {},configureWebpack: config => {if (process.env.NODE_ENV === "production") {// 為生產(chǎn)環(huán)境修改配置config.mode = "production";} else {// 為開發(fā)環(huán)境修改配置config.mode = "development";}Object.assign(config, {// 開發(fā)生產(chǎn)共同配置resolve: {extensions: [".js", ".vue", ".json", ".ts", ".tsx"],alias: {vue$: "vue/dist/vue.js","@": path.resolve(__dirname, "./src"),"@c": path.resolve(__dirname, "./src/components")}}});},// 生產(chǎn)環(huán)境是否生成 sourceMap 文件productionSourceMap: sourceMap,// css相關(guān)配置css: {// 是否使用css分離插件 ExtractTextPluginextract: true,// 開啟 CSS source maps?sourceMap: false,// css預(yù)設(shè)器配置項loaderOptions: {},// 設(shè)置為 false 后你就可以去掉文件名中的 .module 并將所有的 *.(css|scss|sass|less|styl(us)?)requireModuleExtension: false},// use thread-loader for babel & TS in production build// enabled by default if the machine has more than 1 coresparallel: require("os").cpus().length > 1,// PWA 插件相關(guān)配置// see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwapwa: {},// webpack-dev-server 相關(guān)配置devServer: {open: true,// 啟動后自動打開瀏覽器host: "localhost",port: 8080,https: false,hotOnly: false,proxy: {// 設(shè)置代理// proxy all requests starting with /api to jsonplaceholder"/api": {target: "http://localhost:3000/",changeOrigin: true,ws: true,pathRewrite: {"^/api": ""}}},before: app => {}},// 第三方插件配置pluginOptions: {// ...} };注意
- TypeScript開發(fā)環(huán)境默認只能識別.ts,.tsx。因此,在導(dǎo)入vue文件的時候,需要加上后綴名.vue
src目錄下:
- shims-tsx.d.ts
作用:允許以.tsx的文件,在vue項目中寫jsx代碼 - shims-vue.d.ts
作用: 告訴TS以.vue為后綴的文件交給vue模塊來處理declare module '*.vue' {import Vue from 'vue'export default Vue }
用法
一:基本用法
使用 Vue.component或 Vue.extend定義組件;
Vue.extend使用基礎(chǔ)的Vue構(gòu)造器,創(chuàng)建一個“子類”,這種方式最接近Vue的單文件組件寫法。
二:基于類的Vue組件用法
vue-class-component 和 vue-property-decorator
安裝:
yarn add vue-class-component vue-property-decorator --save-dev區(qū)別:
-
vue-class-component官方出品(官方文檔)
是 vue 的官方庫,作用是用類的方式編寫組件,提供了Vue、Component等; -
vue-property-decorator社區(qū)出品(文檔)
深度依賴了vue-class-component,拓展出了更多操作符:@Prop、@Emit、@Inject、@Model、@Provide、@Watch
vue-property-decorator可以說是vue-class-component的一個超集,正常開發(fā)時只需使用vue-property-decorator即可。
具備以下幾個裝飾器和功能:
官方文檔:https://www.npmjs.com/package/vue-property-decorator
@Prop
@Prop(options: (PropOptions | Constructor[] | Constructor) = {})
@Prop裝飾器接收一個參數(shù),這個參數(shù)可以有三種寫法:
- PropOptions,可以使用以下選項:type,default,required,validator;
- Constructor[],指定 prop 的可選類型;
- Constructor,例如String,Number,Boolean等,指定 prop 的類型;
示例代碼:
import { Vue, Component, Prop } from 'vue-property-decorator'@Component export default class YourComponent extends Vue {@Prop(Number) readonly propA: number | undefined@Prop({ default: 'default value' }) readonly propB!: string@Prop([String, Boolean]) readonly propC: string | boolean | undefined }等同于:
export default {props: {propA: {type: Number,},propB: {default: 'default value',},propC: {type: [String, Boolean],},}, }@PropSync
@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})
@PropSync裝飾器與@prop用法類似,二者的區(qū)別在于:
- @PropSync 裝飾器接收兩個參數(shù):
- propName: string 表示父組件傳遞過來的屬性名;
- options: Constructor | Constructor[] | PropOptions 與@Prop的第一個參數(shù)一致;
@PropSync 會生成一個新的計算屬性。
示例代碼:
import { Vue, Component, PropSync } from 'vue-property-decorator'@Component export default class YourComponent extends Vue {@PropSync('name', { type: String }) syncedName!: string }等同于:
export default {props: {name: {type: String,},},computed: {syncedName: {get() {return this.name},set(value) {this.$emit('update:name', value)},},}, }@Model
@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})
@Model裝飾器允許我們在一個組件上自定義v-model,接收兩個參數(shù):
- event: string 事件名。
- options: Constructor | Constructor[] | PropOptions 與@Prop的第一個參數(shù)一致。
示例代碼:
import { Vue, Component, Model } from 'vue-property-decorator'@Component export default class YourComponent extends Vue {@Model('change', { type: Boolean }) readonly checked!: boolean }相當(dāng)于:
export default {model: {prop: 'checked',event: 'change',},props: {checked: {type: Boolean,},}, } <template><inputtype="text":value="value"@change="$emit('change', $event.target.value)"/> </template>@Watch
@Watch(path: string, options: WatchOptions = {})
@Watch 裝飾器接收兩個參數(shù):
- path: string 被偵聽的屬性名;
- options?: WatchOptions={} options可以包含兩個屬性 :
immediate?:boolean 偵聽開始之后是否立即調(diào)用該回調(diào)函數(shù);
deep?:boolean 被偵聽的對象的屬性被改變時,是否調(diào)用該回調(diào)函數(shù);
示例代碼:
import { Vue, Component, Watch } from 'vue-property-decorator'@Component export default class YourComponent extends Vue {@Watch('child')onChildChanged(val: string, oldVal: string) {}@Watch('person', { immediate: true, deep: true })onPersonChanged1(val: Person, oldVal: Person) {}@Watch('person')onPersonChanged2(val: Person, oldVal: Person) {} }等同于:
export default {watch: {child: [{handler: 'onChildChanged',immediate: false,deep: false,},],person: [{handler: 'onPersonChanged1',immediate: true,deep: true,},{handler: 'onPersonChanged2',immediate: false,deep: false,},],},methods: {onChildChanged(val, oldVal) {},onPersonChanged1(val, oldVal) {},onPersonChanged2(val, oldVal) {},}, }注意: 監(jiān)聽發(fā)生在beforeCreate勾子之后,created勾子之前
@Provide
@Provide(key?: string | symbol)
@Inject
@Inject(options?: { from?: InjectKey, default?: any } | InjectKey)
@ProvideReactive
@Provide(key?: string | symbol)
@InjectReactive
@InjectReactive(options?: { from?: InjectKey, default?: any } | InjectKey)
@Emit
@Emit(event?: string)
- @Emit 裝飾器接收一個可選參數(shù),該參數(shù)是Emit的第一個參數(shù),充當(dāng)事件名。如果沒有提供這個參數(shù),Emit的第一個參數(shù),充當(dāng)事件名。如果沒有提供 這個參數(shù),Emit的第一個參數(shù),充當(dāng)事件名。如果沒有提供這個參數(shù),Emit會將回調(diào)函數(shù)名的camelCase轉(zhuǎn)為kebab-case,并將其作為事件名;
- @Emit會將回調(diào)函數(shù)的返回值作為第二個參數(shù),如果返回值是一個Promise對象,$emit會在Promise對象被標(biāo)記為resolved之后觸發(fā);
- @Emit的回調(diào)函數(shù)的參數(shù),會放在其返回值之后,一起被$emit當(dāng)做參數(shù)使用。
@Ref
@Ref(refKey?: string)
@Ref 裝飾器接收一個可選參數(shù),用來指向元素或子組件的引用信息。如果沒有提供這個參數(shù),會使用裝飾器后面的屬性名充當(dāng)參數(shù)
@Component
@Component(options:ComponentOptions = {})
@Component 裝飾器可以接收一個對象作為參數(shù),可以在對象中聲明 components ,filters,directives等未提供裝飾器的選項,也可以聲明computed,watch等
Mixins
三: 兩種用法的區(qū)別
參考地址
Vue.extend()
vue-class-component/vue-property-decorator
總結(jié)
以上是生活随笔為你收集整理的TypeScript+Vue的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快速学习-在线人数统计
- 下一篇: python库读取cif文件_技术专栏: