JavaScript/vue.js/Provide Inject:修订间差异
来自康健生活
| (未显示同一用户的3个中间版本) | |||
| 第1行: | 第1行: | ||
== | == 默认值 == | ||
在 TS 中使用 Inject 时经常会遇到 undefined 的问题,这个时候就需要使用一个默认值来进行消除。 | |||
<syntaxhighlight lang="javascript"> | |||
// eq: | |||
inject(curKey, ref('$'))</syntaxhighlight> | |||
== ref == | == ref == | ||
配置文件 | 配置文件 | ||
| 第83行: | 第89行: | ||
{{hc|head=conf.ts|output=<syntaxhighlight lang="javascript"> | {{hc|head=conf.ts|output=<syntaxhighlight lang="javascript"> | ||
import { type InjectionKey, type Reactive } from 'vue' | import { type InjectionKey, type Reactive } from 'vue' | ||
export interface | export interface IFLineList { | ||
horizontal: number[] | |||
vertical: number[] | |||
} | |||
export interface IFLineListProvide { | |||
lineList: Reactive<IFLineList> | |||
updateLineList: Function | |||
} | } | ||
export const | export const lineListKey: InjectionKey<IFLineListProvide> = Symbol('lineList') | ||
export const DEFAULT_LINELIST = { | |||
lineList: { | |||
horizontal: [] as number[], | |||
vertical: [] as number[], | |||
}, | |||
updateLineList: () => {}, | |||
} | } | ||
</syntaxhighlight>}} | </syntaxhighlight>}} | ||
| 第102行: | 第111行: | ||
<syntaxhighlight lang="html5"> | <syntaxhighlight lang="html5"> | ||
<script lang="ts" setup> | <script lang="ts" setup> | ||
import { provide, reactive | import { provide, reactive } from 'vue' | ||
import { | import { lineListKey, DEFAULT_LINELIST } from './config' | ||
... | ... | ||
const | const lineList = reactive<IFLineList>(DEFAULT_LINELIST.lineList) | ||
const updateLineList = () => {} | |||
provide(lineListKey, { | |||
lineList, | |||
updateLineList, | |||
}) | }) | ||
</script> | </script> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| 第121行: | 第128行: | ||
<script lang="ts" setup> | <script lang="ts" setup> | ||
import { inject, reactive } from 'vue' | import { inject, reactive } from 'vue' | ||
import { | import { lineListKey, DEFAULT_LINELIST } from './config' | ||
... | ... | ||
const | const { lineList, updateLineList } = inject(lineListKey, DEFAULT_LINELIST) | ||
</script> | </script> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== 扩展 == | |||
在网上看到一种扩展的思路,留存以做思考。 | |||
<syntaxhighlight lang="javascript"> | |||
// in utils.ts | |||
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; | |||
} | |||
// Another vue file | |||
import { injectStrict } from './utils.ts'; | |||
const product = injectStrict(ProductKey); | |||
product.value; </syntaxhighlight>{{Unknown}} | |||