JavaScript/vue.js/Provide Inject
来自康健生活
< JavaScript | vue.js
默认值
在 TS 中使用 Inject 时经常会遇到 undefined 的问题,这个时候就需要使用一个默认值来进行消除。
// eq:
inject(curKey, ref('$'))
ref
配置文件
conf.ts
import { type InjectionKey, type Ref } from 'vue'
export const DEFAULT_PARAMS = 1
export const valueKey = Symbol('value_symbol_string') as InjectionKey<Ref<number>>
父组件,上级组件
<script lang="ts" setup>
import { provide, ref } from 'vue'
import { DEFAULT_PARAMS, valueKey } from './config'
...
const valueRef = ref(props.params || DEFAULT_PARAMS)
provide(valueKey, valueRef)
</script>
子组件
<script lang="ts" setup>
import { inject, ref } from 'vue'
import { DEFAULT_PARAMS, valueKey } from './config'
...
const value= inject(valueKey, ref(DEFAULT_PARAMS))
</script>
reactive
配置文件
conf.ts
import { type InjectionKey, type Reactive } from 'vue'
export interface IFRect {
x: number
y: number
width: number
height: number
}
export const DEFAULT_RECT = {
x: 0,
y: 0,
width: 0,
height: 0,
}
export const rectKey: InjectionKey<Reactive<IFRect>> = Symbol('rect')
父组件,上级组件
<script lang="ts" setup>
import { provide, reactive, type PropType } from 'vue'
import { DEFAULT_RECT, rectKey, type IFRect } from './config'
...
const props = defineProps({
rect: {
type: Object as PropType<IFRect>,
default: () => DEFAULT_RECT as IFRect,
},
})
const rectReactive = reactive(props.rect || DEFAULT_RECT)
provide(rectKey, rectReactive)
</script>
子组件
<script lang="ts" setup>
import { inject, reactive } from 'vue'
import { DEFAULT_RECT, rectKey } from './config'
...
const rect = inject(rectKey, reactive(DEFAULT_RECT))
</script>
function
配置文件
conf.ts
import { type InjectionKey, type Reactive } from 'vue'
export interface IFLineList {
horizontal: number[]
vertical: number[]
}
export interface IFLineListProvide {
lineList: Reactive<IFLineList>
updateLineList: Function
}
export const lineListKey: InjectionKey<IFLineListProvide> = Symbol('lineList')
export const DEFAULT_LINELIST = {
lineList: {
horizontal: [] as number[],
vertical: [] as number[],
},
updateLineList: () => {},
}
父组件,上级组件
<script lang="ts" setup>
import { provide, reactive } from 'vue'
import { lineListKey, DEFAULT_LINELIST } from './config'
...
const lineList = reactive<IFLineList>(DEFAULT_LINELIST.lineList)
const updateLineList = () => {}
provide(lineListKey, {
lineList,
updateLineList,
})
</script>
子组件
<script lang="ts" setup>
import { inject, reactive } from 'vue'
import { lineListKey, DEFAULT_LINELIST } from './config'
...
const { lineList, updateLineList } = inject(lineListKey, DEFAULT_LINELIST)
</script>
扩展
在网上看到一种扩展的思路,留存以做思考。
function injectStrict<T>(key: InjectionKey<T>, fallback?: T) {
const resolved = inject(key, fallback);
if (!resolved) {
throw new Error(`Could not resolve ${key.description}`);
}
return resolved;
}
(来源摘自互联网示例,作者 未知)
No categories