Appearance
TS 在 Vue3 中应用
Inject & Provide
typescript
// types/provide
export type formatDateFunc = (v: number | string) => string
export const formateDateKey: InjectionKey<formatDateFunc> = Symbol('formateDate')1
2
3
2
3
javascript
// provide
import { formatDateFunc, formateDateKey } from './types/provide'
const formatDate: formatDateFunc = (v) => {
const value = new Date(v)
return value === 'Invalid Date' ? '暂无' : value
}
provide(formateDateKey, formatDate)1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
javascript
// inject
const format = inject(formateDateKey)
// Cannot invoke an object which is possibly 'undefined'.ts(2722)
format?.(utime)1
2
3
4
5
2
3
4
5
defineProps not defined
参考:https://eslint.vuejs.org/user-guide/#does-not-work-well-with-script-setup
以前:
js
// .eslintrc.js
module.exports = {
parser: 'vue-eslint-parser',
parserOptions: {
// Parser that checks the content of the <script> tag
parser: '@typescript-eslint/parser',
sourceType: 'module',
ecmaVersion: 2020
},
env: {
// ...
'vue/setup-compiler-macros': true // <-
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
现在:
js
// .eslintrc.js
module.exports = {
parser: 'vue-eslint-parser',
parserOptions: {
parser: 'espree', // <-
ecmaVersion: 2022, // <-
sourceType: 'module'
}
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
自定义组件中枚举 prop
自定义组件中枚举值处理
js
const props = defineProps({
mode: {
type: String as PropType<'matrix' | 'country'>,
required: true
}
})1
2
3
4
5
6
2
3
4
5
6
defineExpose
import type 导入
ts
import type MyComponent from '..'
const myRef = ref<typeof MyComponent>()1
2
2
import 导入
ts
import MyComponent from '..'
const myRef = ref<InstanceType<typeof MyComponent>>()1
2
2