JavaScript/vue.js/Provide Inject:修订间差异
来自康健生活
| 第28行: | 第28行: | ||
... | ... | ||
const value= inject(valueKey, ref(DEFAULT_PARAMS)) | const value= inject(valueKey, ref(DEFAULT_PARAMS)) | ||
</script> | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| 第72行: | 第73行: | ||
<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 { DEFAULT_RECT, rectKey } from './config' | ||
... | |||
const rect = inject(rectKey, reactive(DEFAULT_RECT)) | |||
</script> | |||
</syntaxhighlight> | |||
=== function === | |||
配置文件 | |||
{{hc|head=conf.ts|output=<syntaxhighlight lang="javascript"> | |||
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') | |||
</syntaxhighlight>}} | |||
父组件,上级组件 | |||
<syntaxhighlight lang="html5"> | |||
<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> | |||
</syntaxhighlight> | |||
子组件 | |||
<syntaxhighlight lang="html5"> | |||
<script lang="ts" setup> | |||
import { inject, reactive } from 'vue' | |||
import { DEFAULT_RECT, rectKey } from './config' | |||
... | ... | ||
const rect = inject(rectKey, reactive(DEFAULT_RECT)) | const rect = inject(rectKey, reactive(DEFAULT_RECT)) | ||
</script> | </script> | ||
</syntaxhighlight> | </syntaxhighlight> | ||