本文介绍了TypeScript在Vue中的简单使用,Html模板和CSS样式没有变化,主要是 javascript 部分转变成了类的形式。
- 基本模板
以下是props、data、computed、watch、周期函数、方法、混入、过滤器等在 ts 模板中的基本写法。
<template>
<div class="test">
<h1>This is an about page</h1>
<ts-child title="子组件" @publish="handlePublish"></ts-child>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import TsChild from './ts-child.vue'
import * as filters from '@/filters/filters'
// 给@Component传入一个对象,设置组件名、自定义属性、混入、子组件等
@Component({
// 组件名
name: 'TSComponent',
// 自定义属性
componentName: 'TSComponent',
// 混入
mixins: [],
// 子组件
components: {
TsChild
},
// 过滤器
filters: filters
})
export default class extends Vue { // 采用类的结构,class后面可以写类名,也可以省略
/********************* props *********************/
// props属性需单独写,用解释器@形式,()中是prop的属性,以对象的形式传入
// !和?的用法,请学习typescript相关知识
@Prop() value!: string
// 必传prop示例
@Prop({ required: true }) title!: string
// prop默认值示例
@Prop({ default: () => ({}) }) options?: object
/********************* data *********************/
// data中的定义的变量,转变为类的属性,可在前面加上private、public、protected等关键字
private inputValue = this.value
private list = []
/********************* computed *********************/
// 方法前面加上get和set就表示为computed计算属性,get为获取计算属性值,set为设置
get showTitle () {
return this.title
}
set showTitle (val) {
this.title = val
}
/********************* watch *********************/
// 用解释器@watch单独定义
@Watch('value')
private onValueChange(value: string, oldValue: string) {
this.inputValue = value
}
// watch中需要写属性的写法
@Watch('options', { immediate: true, deep: true })
private onOptionsChange(value: string, oldValue: string) {
// doSomething...
}
/********************* 生命周期函数 *********************/
created () {
// doSomething...
}
mounted () {
// doSomething...
}
beforeDestroy () {
// doSomething...
}
/********************* methods *********************/
handlePublish () {
// doSomething...
}
}
</script>
- 过滤器的写法
过滤器可以直接在@Component中定义:
@Component({
filters: {
filterOne: () => {},
filterTwo: () => {}
}
})
当然,为了代码的简洁和方便管理,建议将过滤器提取出来,单独写在一个ts文件中,导入使用:
// @/filters/filters.ts
export const uppercaseFirstChar = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1)
}
export const formatMoney = (str: string) => {
return `¥${str}`
}
导入时,可以采用全部导入,也可以按需导入:
// 导入形式一
import * as filters from '@/filters/filters'
@Component({
filters: filters
})
// 导入形式二
import { uppercaseFirstChar, formatMoney } from '../filters/filters'
@Component({
filters: {
uppercaseFirstChar,
formatMoney
}
})
- 自定义属性
如果你熟悉 Element UI 的代码,会发现其中大量使用到了自定义属性 componentName ,假如你也想自己定义一个属性,那么可以参考下面的写法:
declare module 'vue/types/options' {
interface ComponentOptions<V extends Vue> {
componentName?: string
}
}
在多个地方都要使用自定义属性的时候,建议将该声明提取成单独的ts文件,在使用的地方导入即可。
以上内容,仅供参考,如有帮助,不胜荣幸!