vue结合typescript的小项目记录

前端开发
2020年03月05日
0

项目地址:https://github.com/humandetail/vue-ts-cart-demo

效果图:

vue+ts-1

什么是TypeScript

TypeScript是一种由微软开发的开源、跨平台的编程语言。它是JavaScript的超集,最终会被编译为JavaScript代码。TypeScript添加了可选的静态类型系统、很多尚未正式发布的ECMAScript新特性(如装饰器 ) 。

Vue中使用TypeScript

创建应用

VueCli3起,我们在创建Vue应用时可以选择TypeScript依赖。

shell
vue create demo # window用户可以使用以下命令 winpty vue.cmd create demo

vue+ts-2

组件示例

vue
<template> <!-- 结构示例,指令基础用法同vue --> <div class="minos-system-setting" v-if="hideHeader"> <h3>结构示例</h3> <span>{{ selfKey1 }}</span> <ul> <li :key="item" v-for="item in fatherKey">{{ item }}</li> </ul> <button @click="addText">追加文字</button> <AnotherVue :class="['default-class', selfKey1.length > 10 ? 'one' : 'two']" /> </div> </template> <script lang="ts"> import { Component, Vue, Prop, Watch } from "vue-property-decorator"; import { Route } from "vue-router"; import AnotherVue from "@/components/AnotherVue.vue"; @Component({ // 组件注册 components: { AnotherVue // 'another-vue': AnotherVue }, // 过滤器 filters: { filterFn1() {} }, // 属性传递 props: { hideHeader: { type: Boolean, required: false, default: false // 默认属性的默认值 } } }) export default class ComponentName extends Vue { @Prop({ type: Boolean, required: false, default: false // 默认属性的默认值 }) private hideHeader!: boolean | undefined; @Prop() private fatherKey: string[]; // 其他没有默认值的传值 private selfKey1: string = "自己的一个变量"; // 生命周期 created() {} mounted() {} // 计算属性 get computedKey() { return this.selfKey1.length; } // 监听器 @Watch("computedKey") getcomputedKey (newVal) { console.log(newVal); } // 导航守卫函数 private beforeRouteEnter(to: Route, from: Route, next: () => void): void { console.log("beforeRouteEnter", to, from, next); next(); } // 方法 addText() { this.selfKey1 += ',追加文字!'; } } </script> <style lang="scss" scoped> @import "@/assets/styles/demo.scss"; </style>

要加上!而不是使用?

typescript
export default class Test extends Vue { @Prop() private count: number; } // Property 'count' has no initializer and is not definitely assigned in the constructor export default class Test extends Vue { @Prop() private count?: number; // count: number | undefined } export default class Test extends Vue { @Prop() private count!: number; // count: number }

!是和?相对的,是typescript的语法,表示强制解析(也就是告诉typescript编译器,我这里一定有值)。你写?的时候再调用,typescript会提示可能为undefined

事件对象如何注解

typescript
function handleInput (ev: Event): void { let e: Event = ev || window.event, tar = (e.target || e.srcElement) as HTMLInputElement, value = Number(tar.value); }

bus总线机制如何使用

借助vue-bus-ts

shell
npm i -S vue-bus-ts

main.ts

typescript
import Vue from 'vue'; import App from './App.vue'; import router from './router'; import EventBus from 'vue-bus-ts'; import './assets/styles/common.scss'; Vue.config.productionTip = false; // 使用总线机制 Vue.use(EventBus); const bus = new EventBus.Bus(); new Vue({ router, bus, render: h => h(App) }).$mount('#app');