前言
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 => {};