JavaScript/vue.js/Provide Inject:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的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 IFRect {
export interface IFLineList {
   x: number
   horizontal: number[]
   y: number
   vertical: number[]
   width: number
}
   height: number
export interface IFLineListProvide {
   lineList: Reactive<IFLineList>
   updateLineList: Function
}
}
export const DEFAULT_RECT = {
export const lineListKey: InjectionKey<IFLineListProvide> = Symbol('lineList')
   x: 0,
export const DEFAULT_LINELIST = {
  y: 0,
   lineList: {
   width: 0,
    horizontal: [] as number[],
   height: 0,
    vertical: [] as number[],
   },
   updateLineList: () => {},
}
}
export const rectKey: InjectionKey<Reactive<IFRect>> = Symbol('rect')
</syntaxhighlight>}}
</syntaxhighlight>}}


第102行: 第111行:
<syntaxhighlight lang="html5">
<syntaxhighlight lang="html5">
<script lang="ts" setup>
<script lang="ts" setup>
import { provide, reactive, type PropType } from 'vue'
import { provide, reactive } from 'vue'
import { DEFAULT_RECT, rectKey, type IFRect } from './config'
import { lineListKey, DEFAULT_LINELIST } from './config'
...
...
const props = defineProps({
const lineList = reactive<IFLineList>(DEFAULT_LINELIST.lineList)
  rect: {
const updateLineList = () => {}
    type: Object as PropType<IFRect>,
provide(lineListKey, {
    default: () => DEFAULT_RECT as IFRect,
   lineList,
   },
  updateLineList,
})
})
const rectReactive = reactive(props.rect || DEFAULT_RECT)
provide(rectKey, rectReactive)
</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 { DEFAULT_RECT, rectKey } from './config'
import { lineListKey, DEFAULT_LINELIST } from './config'
...
...
const rect = inject(rectKey, reactive(DEFAULT_RECT))
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}}