【vue3学习系列】集成TypeScript的vue3一些写法上的记录

前言

vue3中需不需要加入TS,要根据项目的实际需求去进行衡量,如果需要使用到静态类型的检测和环境声明等,可以加入,不过也增加了代码的复杂度。

props

import { PropType } from "vue";

export default defineComponent({
	props: {
		  str: {
		    type: String as PropType<string>, // 声明ts类型
		    default: "default",
		    required: true
		  },
	}
})
  • type:在type中直接写构造函数代表类型是JS的写法,不符合TS,所以要通过类型断言并借助PropType传入泛型来定义类型。如果是object的话,传入的泛型应该是个interface
  • required:这个的作用不只是声明组件必传参数,还有一个作用是,在通过props.str获取的值时,就不需要先用if(props.str)去判断是否有值,如果不使用required的话,ts会提示你这个str可能取不到值。

如果想把props的内容拿出来单独写个对象,那么有个关键点:

const PropsType = {
	str: String,
	num: {
		type: Number,
		required: true
	}
} as const // 关键就是这个as const,先死记,以后再去弄清楚原因

export default defineComponent({
	props: PropsType
})

vuex

这里记录modules的写法,首先在index.ts中:

import { createStore } from "vuex";

import A from "./modules/A"; // 模块A
import B from "./modules/B"; // 模块B

/* 定义最外层的state接口 */
export interface IRootState {
  num: number;
}

export default createStore<IRootState>({
  state: {
    num: 1,
  },
  mutations: {},
  actions: {},
  modules: {
    A,
    B,
  },
});

在A模块中:

import { createStore, Commit, Module } from "vuex";

import { IRootState } from "../index"; // 引入vuex主入口的state接口

interface ILoginState { // state接口
  num: number;
}

const A: Module<ILoginState, IRootState> = { // 这里是关键,要同时传入A的state接口和vuex主入口的state接口
  state: {
    num: 2,
  },
  getters: {},
  mutations: {
  },
  actions: {
    FN({ commit }, payload) {
    },
  },
};

export default A;

传值类型

如果要把一个响应式类型作为类型约束:

import { Ref } from "vue";
interface Result {
  num: Ref<boolean>;
}

如果把一个计算属性作为类型:

import { ComputedRef } from "vue";
const Fn = (
  com: ComputedRef<number>
): Result => {};
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值