vue之typescript配置和使用

vue之typescript配置和使用

目前笔者在找前端工程师工作(vue方向),发现许多公司都要求会使用TypeScript,花了一点时间把TypeScript看完了,今天将介绍vue中typescript使用

第一步,在创建项目时选中typescript,如下:
在这里插入图片描述第二步,在安装装饰器来简化书写

npm install vue-class-component  vue-property-decorator

第三步,改写代码,将创建初始项目里面HelloWorld.vue里面写个简单计数器,代码如下:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
		<button @click="decrement"> - </button>
		{{count}}
		<button @click="increment"> + </button>
  </div>
</template>

<script lang="ts">
 import { Component, Prop, Vue, Watch, Emit } from "vue-property-decorator";

@Component
export default class HelloWorld extends Vue {
	public count:Number = 0
	@Prop() private msg: String | undefined
	
	public increment ():void {
		this.count++
	}
	public decrement ():void {
		this.count--
	}
}
</script>

第四步,改写Home.vue

<template>
  <div class="home">
    <HelloWorld msg="vue from TypeScript"/>
  </div>
</template>

<script lang="ts">
 import { Component, Prop, Vue, Watch, Emit } from "vue-property-decorator";
import HelloWorld from '@/components/HelloWorld.vue'

@Component({
	components: {
		HelloWorld
	},
	beforeRouteLeave(to: any, from: any, next: any) {
		console.log('beforeRouteLeave');
		next();
	},
	beforeRouteEnter(to: any, from: any, next: any) {
		console.log('beforeRouteEnter');
		next();
	}
})
export default class Home extends Vue {
	
}
</script>

本文章只是简单说明vue中使用typescript,装饰器还有许多用法,可自行查阅

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3 和 TypeScript 配合使用可以提高代码的可读性、可维护性和健壮性。下面我给你提供一些配合使用的方法: 1. 使用 Vue CLI 创建项目时,选择 TypeScript 选项,这样就可以自动生成 TypeScript配置文件,并且在编写组件时也能享受到 TypeScript 的类型检查。 2. 在组件中使用 TypeScript,可以先定义组件的 props 和 data 的类型,这样在编写组件时就能享受到 TypeScript 的类型检查,例如: ```typescript <template> <div>{{ message }}</div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ props: { name: { type: String, required: true } }, data() { return { message: `Hello ${this.name}!` } } }) </script> ``` 3. 在 Vue3 中,使用 Composition API 编写组件时,也可以结合 TypeScript 使用,例如: ```typescript <template> <div>{{ message }}</div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' export default defineComponent({ props: { name: { type: String, required: true } }, setup(props) { const message = ref(`Hello ${props.name}!`) return { message } } }) </script> ``` 4. 如果你使用了第三方库,并且该库没有提供类型声明文件,可以手动创建一个类型声明文件,例如: ```typescript // my-library.d.ts declare module 'my-library' { export function myFunction(): void } ``` 这样在使用该库时就能享受到 TypeScript 的类型检查。 总之,Vue3 和 TypeScript 配合使用可以提高代码的可读性、可维护性和健壮性,建议在项目中使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值